Yii2 params access within local config file in common directory

百般思念 提交于 2019-11-29 10:15:53

The config files are read before the application is instantiated as explained in the request lifecycle:

  1. A user makes a request to the entry script web/index.php.
  2. The entry script loads the application configuration and creates an application instance to handle the request.
  3. The application resolves the requested route with the help of the request application component.
  4. ...

As such \Yii::$app does not yet exist hence the error. I would suggest moving your api_key definition to the main-local.php config such that there is no confusion over where it is being set:

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

Alternatively, you can use Yii2's dependancy injection container to set the apikey in your application's entry script:

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

The params is a part of config and you can not call this in your config .

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

myClass:

class myClass extends ... {

    public $apikey;

    public function __construct(){
        $this->apikey =  \Yii::$app->params['mandrill_api_key'];
    }


}

You can just do

$params['mandrill_api_key'] 

you dont need to use

\Yii::$app->params['mandrill_api_key']
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!