Yii2:模块内部的可配置模型 [英] Yii2: Configurable models inside module

查看:105
本文介绍了Yii2:模块内部的可配置模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以可配置的方式将模型/活动记录包含在Yii2模块中的最佳实践是什么?

What is the best practice of including models/activerecords within a Yii2 module in a way that they are configurable?

这些只是我们想使用模块中包含的activerecord时遇到的一些问题:

These are just some of the problems we face when we want to use an activerecord included inside a module:

  1. 添加事件和模块提供的模型/活动记录的行为.我想使用Yii2的配置格式.该怎么办?

定义与模块外部存在的模型/活动记录的关系.将模块中包含的活动记录链接到用户活动记录时,我们可以依靠Ỳii::$app->user->identityClass,但是对于其他自定义关系,我们可能需要扩展活动记录.有没有更好的办法?从模块扩展activerecord类有点违反模块化的目的.

Defining relations with models/activerecords that exist outside of the module. When linking an activerecord contained inside a module to the User activerecord we can rely on Ỳii::$app->user->identityClass, but for other custom relations we might need to extend the activerecord. Is there any better approach? Extending activerecord classes from modules somewhat defeats the purpose of modularity.

在模块/activerecord中配置各种其他变量.假设我们要调整最大字符串长度验证值.在模块控制器中,我们始终可以使用$this->module->params来读取任何自定义值,但是我们不能从Model或ActiveRecord中执行此操作.我们应该怎么做呢?

Configuring various other variables within the module/activerecord. Let's say we want to adjust the max string length validation value. In a module Controller, we can always use $this->module->params to read any custom value, but we cannot do this from a Model or an ActiveRecord. What are we supposed to do instead?

推荐答案

我认为您可能最终会使用

I think you might end up using dependency injection:

写一个扩展名"\ common \ extensions \ MyBootstrap":

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");
    }
}

添加到您的配置中:

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

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

,并且在您的代码中必须使用Yii::$container->get():

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

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

,它将创建Test2模型而不是Test1. 如果您希望ActiveRecord发生这种情况,请覆盖以下内容:

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);
}

这篇关于Yii2:模块内部的可配置模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆