且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

yii2.动态地向模型添加属性和规则

更新时间:2023-12-02 23:01:40

向现有模型添加动态属性

当您想在运行时向现有模型添加动态属性时.然后你需要一些自定义代码,你需要:一个模型类和一个扩展类,它将做动态部分,并有数组来保存动态信息.这些数组将在需要的函数中与模型类的返回数组合并.

Add Dynamic Attributes to a existing Model

When you want to add dynamic attributes during runtime to a existing model. Then you need some custom code, you need: A Model-Class, and a extended class, which will do the dynamic part and which have array to hold the dynamic information. These array will merged in the needed function with the return arrays of the Model-Class.

这是一种模型,它并不完全有效.但也许你知道你需要做什么:

Here is a kind of mockup, it's not fully working. But maybe you get an idea what you need to do:

class MyDynamicModel extends MyNoneDynamicModel
{

private $dynamicFields = [];
private $dynamicRules = [];

public function setDynamicFields($aryDynamics) {
     $this->dynamicFields = $aryDynamics;
}

public function setDynamicRules($aryDynamics) {
     $this->dynamicRules = $aryDynamics;
}

public function __get($name)
{
    if (isset($this->dynamicFields[$name])) {
        return $this->dynamicFields[$name];
    }

    return parent::__get($name);
}

public function __set($name, $value)
{
if (isset($this->dynamicFields[$name])) {
  return $this->dynamicFields[$name] = $value;
}
return parent::__set($name, $value);
}

public function rules() {
  return array_merge(parent::rules, $this->dynamicRules);
}
}

完整的动态属性

当所有属性都是动态的并且您不需要数据库时.然后使用 Yii2 的新 DynamicModel.该文档还指出:

DynamicModel 是一个模型类,主要用于支持临时数据验证.

DynamicModel is a model class primarily used to support ad hoc data validation.

这是一个完整的表单集成示例来自 Yii2-Wiki,所以我不在这里举个例子.

Here is a full example with form integration from the Yii2-Wiki, so i don't make a example here.

当您想向模型添加属性时,该属性不在数据库中.然后只需在模型中声明一个公共变量:

When you want to add a attribute to the model, which is not in the database. Then just declare a public variable in the model:

public $myVirtualAttribute;

然后您可以像其他(数据库-)属性一样在规则中使用它.

Then you can just use it in the rules like the other (database-)attributes.

要做大规模赋值 不要忘记在模型规则中添加安全规则:

To do Massive Assignment don't forget to add a safe rule to the model rules:

public function rules()
{
    return [
        ...,
        [['myVirtualAttribute'], 'safe'],
        ...
    ];
}

这里很好地解释了原因:Yii2 非数据库(或虚拟)属性在大规模赋值期间未填充?

The reason for this is very well explained here: Yii2 non-DB (or virtual) attribute isn't populated during massive assignment?