8

I'm using Yii2 advanced template, I want to access params.php in main-local.php file, I called this ways:

main-local.php:

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

and I have stored 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'm getting this error:

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

What should I do to access these parameters?

ankitr
  • 5,992
  • 7
  • 47
  • 66
Muhammad Shahzad
  • 9,340
  • 21
  • 86
  • 130

3 Answers3

3

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();
topher
  • 14,790
  • 7
  • 54
  • 70
3

You can just do

$params['mandrill_api_key'] 

you dont need to use

\Yii::$app->params['mandrill_api_key']
huss
  • 31
  • 1
  • This should be the accepted answer. Yii2 config loads the params file at starting main-config script $params = require(__DIR__ . '/params.php'); So you can use $params array in any part of your file – Leonardo Sapuy Oct 08 '17 at 18:26
1

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'];
    }


}
Amir Mohsen
  • 853
  • 2
  • 9
  • 23