Yii2: Configurable models inside module

北战南征 提交于 2019-12-01 14:26:34
e-frank

I think you might end up using dependency injection:

Write an extension "\common\extensions\MyBootstrap":

namespace common\extensions;

use Yii;
use yii\base\BootstrapInterface;
use yii\base\Application;

class MyBootstrap implements BootstrapInterface {
    /**
     * @param  Application $app Application
     **/
    public function bootstrap($app) {
        Yii::$container->set("common\\modules\\test\\models\\Test1", "common\\modules\\test\\models\\Test2");
    }
}

add to your config:

'bootstrap' => [
    'common\extensions\MyBootstrap',
],

'components' => [ 
    //  ... 
]

and in your code you have to use Yii::$container->get():

$test = Yii::$container->get('common\modules\test\models\Test1');
var_dump($test);

which will create Test2 model instead of Test1. If you want this to happen for your ActiveRecord, override this:

public static function instantiate($row) {
    return \Yii::$container->get(static::class);
}

EDIT: The underlying issue has now been resolved. We can use DI to inject relations into ActiveRecords.

As of July 2017, Yii2 does not allow ActiveRecord dependency injection!

See:

The only way around this is to configure your modules through your Yii::$app->params and then use those values inside module ARs (eg. when doing validation).

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