Yii2 provides access to parameters in a local configuration file in a shared directory

I use the extended Yii2 template, I want to access params.php in the main-local.php file, I called it ways:

Main-local.php:

 'mailer' => [ 'class' => 'myClass', 'apikey' => \Yii::$app->params['mandrill_api_key'], 'viewPath' => '@common/mail', ], 

and I saved this mandrill_api_key in params.php

params.php:

 <?php return [ 'adminEmail' => ' admin@example.com ', 'supportEmail' => ' support@example.com ', 'user.passwordResetTokenExpire' => 3600, 'mandrill_api_key' => 'mykey' ]; 

I get this error:

Note. Trying to get a non-object property in C: \ xampp \ htdocs \ myproject \ common \ config \ main-local.php on line 25

What should I do to access these options?

+7
yii2 yii2-advanced-app
source share
3 answers

Configuration files are read before the application is instantiated, as described in the request life cycle :

  • The user makes a request to write the script web / index.php.
  • The script entry loads the application configuration and creates an application instance to process the request.
  • The application resolves the requested route using the request application component.
  • ...

As such, \Yii::$app does not yet exist, hence the error. I would suggest moving the api_key definition to the main-local.php so that there is no confusion about where it is installed:

 'mailer' => [ 'class' => 'myClass', 'apikey' => 'actual api key', 'viewPath' => '@common/mail', ], 

Alternatively, you can use the YII2 dependency injection container to set apikey in your script application entry:

 ... $app = new yii\web\Application($config); \Yii::$container->set('\fully\qualified\myClass', [ 'apikey' => \Yii::$app->params['mandrill_api_key'], ]); $app->run(); 
+3
source share

Paramas are part of the configuration, and you cannot invoke this in your configuration.

the best way for handel is you can use in your class:

MyClass:

 class myClass extends ... { public $apikey; public function __construct(){ $this->apikey = \Yii::$app->params['mandrill_api_key']; } } 
+2
source share

You can just do

 $params['mandrill_api_key'] 

you do not need to use

 \Yii::$app->params['mandrill_api_key'] 
+2
source share

All Articles