Yii :: configure not working in init () module

I have an API for modules and I want to load a config file for it. The manual says that I need to use the \ Yii :: configure function. I use it, but it doesn't apply any new configurations. And I tried to use an array instead of a config file, the result is the same

class API extends \yii\base\Module
{
    public $controllerNamespace = 'api\client\controllers';

    public function init()
    {
        parent::init();

//        \Yii::configure($this, require(__DIR__ . '/config/main.php'));

        \yii::configure($this, [
            'components' => [
                'user' => [
                    'class' => 'yii\web\UserTest',
                    'identityClass' => 'api\client\models\User',
                ],
            ]
        ]);

        echo \yii::$app->user->className();

        die();
    }
}

      

How can I override the config in my module?

+3


source to share


2 answers


UPDATE

You need to use setComponents method for Yii :: $ app

    Yii::$app->setComponents(
        [
            'errorHandler'=>[
                'errorAction'=>'forum/forum/error',
                'class'=>'yii\web\ErrorHandler',
            ],     
            'user' => [
                'class' => 'yii\web\User',
                'identityClass' => 'app\modules\profile\models\User',
            ],
        ]
    ); 

      



OLD ANSWER

Didn't that lead to errors? Your corpus is wrong, so instead of "yii" in small letters, use "Yii" with a capital letter

class API extends \yii\base\Module
{
    public $controllerNamespace = 'api\client\controllers';

    public function init()
    {
        parent::init(); 

        \Yii::configure($this, [
            'components' => [
                'user' => [
                    'class' => 'yii\web\UserTest',
                    'identityClass' => 'api\client\models\User',
                ],
            ]
        ]);

        echo \Yii::$app->user->className();

        die();
    }
}

      

+2


source


I see no reason to override application components here. I would use @StefanoMtangoo's trick, but to install the component to the module itself instead of Yii::$app

:

public function init()
{
    parent::init();

    $this->setComponents([
        'db' => [
            'class' => 'yii2tech\filedb\Connection',
            'path' => '@app/builder/data',
        ]
    ]);
}

      

Then the tricky part is to distinguish between any components of the application and the native components of your module. For example, if my module had a model extending yii \ db \ ActiveRecord , I would override getDB () as follows (source code here ):



public static function getDb()
{
    return Yii::$app->getModule('api')->get('db');
    // instead of: return Yii::$app->getDb();
}

      

So, no matter which application using my module has or does not have a component db

, it doesn't matter.

0


source







All Articles