Yii2:模块内的可配置模型 [英] Yii2: Configurable models inside module
问题描述
在 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:
添加事件和模块提供的模型/活动记录的行为.我想使用 Yii2 的 配置格式.如何做到这一点?
定义与模块外部存在的模型/活动记录的关系.当将包含在模块中的 activerecord 链接到 User activerecord 时,我们可以依赖 Ỳii::$app->user->identityClass
,但对于其他自定义关系,我们可能需要扩展 activerecord.有没有更好的办法?从模块扩展 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.
在模块/活动记录中配置各种其他变量.假设我们要调整最大字符串长度验证值.在模块控制器中,我们总是可以使用 $this->module->params
读取任何自定义值,但我们不能从模型或 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:
编写一个扩展commonextensionsMyBootstrap":
Write an extension "commonextensionsMyBootstrap":
namespace commonextensions;
use Yii;
use yiiaseBootstrapInterface;
use yiiaseApplication;
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' => [
'commonextensionsMyBootstrap',
],
'components' => [
// ...
]
并且在你的代码中你必须使用 Yii::$container->get()
:
and in your code you have to use Yii::$container->get()
:
$test = Yii::$container->get('commonmodules estmodelsTest1');
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屋!