Yii2 set config file for module

2019-06-14 12:56发布

问题:

How can i create my config in Yii2? and return in it for example $new = 'new' and then use it in other class? My structure

 Module
    MyModule
      config (directory)
        config.php (here must be $new = 'new')
      function (directory)
        MyFunc ( here i need use variable from config)

Thanks for help! code from

    <?php
    namespace module\MyModule\function;

    class MyFunc
  {
   private static function func()
    {
   here i need to get $new from config
    }
  }

回答1:

set config file in Module class like below:

class Module extends \yii\base\Module    {
    public function init(){
        parent::init();
        \Yii::configure($this, require __DIR__ . '/config.php');
}

your config file like this:

return [
   'params' => [ 
       'test' => 'this is the test params'
   ],
   'components' => [
     // ...
   ],
];

accessing params in module:

\Yii::$app->getModule('MyModule')->params['test'];


回答2:

Why you config file in module inside? Put configFile in common config directory and this configuration will accassible in you app.