在Laravel模型类中动态添加访问器方法

在Laravel模型类中动态添加访问器方法,laravel,Laravel,我已经构造了一个数组中的函数名,该数组本质上是动态的,这意味着它们可以是2或10,就像这样: 结果 我希望它们驻留在模型类(例如:User)中,如下所示: public function getEmailVerifiedAtAttribute($value) { // ... } public function getCreatedAtAttribute($value) { // ... } public function getUpdatedAtAttribute($value)

我已经构造了一个数组中的函数名,该数组本质上是动态的,这意味着它们可以是2或10,就像这样:

结果 我希望它们驻留在模型类(例如:User)中,如下所示:

public function getEmailVerifiedAtAttribute($value)
{
  // ...
}

public function getCreatedAtAttribute($value)
{
  // ...
}

public function getUpdatedAtAttribute($value)
{
  // ...
}

// ... If there were more in array they would have been constructed dynamically as well.

如果我们可以避免评估,请

在您的模型中执行类似操作可能会取得一些有限的成功:

public function hasGetMutator($key) {
   return parent::hasGetMutator($key) || in_array('get'.Str::studly($key).'Attribute', $youArratOfDynamicMutators);
}

protected function mutateAttribute($key, $value)
{
        if (parent::hasGetMutator($key)) {
           return parent::mutateAttribute($key, $value);
        }
        // Mutate your value here
        return $value;
}
protected function __construct(array $attributes = [])
{
    parent::__construct($attributes);
    $this->casts = array_merge($this->casts, [
        'customCastColumn1' => MyCustomCast::class,
         // ...
    ]);
}
这样做的目的是重写方法
hasGetMutator
,该方法通常只检查类中是否存在函数
'get'.Str::studly($key)。'Attribute'
,如果该函数名存在于数组中,则返回true,并修改
mutateAttribute
函数进行自定义变异(除了执行默认操作之外)

但是,如果您的突变是标准突变,那么我建议您改用:


这将在构建模型时向模型中添加所需的强制转换。

有什么原因不能在此模型上定义这些方法吗?为什么
eval
会起作用?是的,因为我正在开发一个包,在开发之前,我无法知道最终用户希望以某种方式更改的特定类型的字段。您有arra吗访问器的名称是y,但什么会定义它们实际应该做什么?它们不能使用自己的模型(可以根据需要进行更改)有什么原因吗?定义是相同的:比如说``返回ucwords($value);您可以有一个只包含属性名称的数组,您可以重写
getAttribute
来检查该数组并处理这些情况,如果不调用parent
getAttribute
,但我不明白为什么最终用户不能定义他们自己的模型,他们希望[code]trait ConvertFields{public function hasGetMutator($key){dd('$vars');返回$this->hasGetMutator($key)| in_数组('get'.Str::studly($key)。'Attribute',$this->getConvertionFields();}受保护的函数mutateAttribute($key,$value){dd($vars');if($this->hasGetMutator($key)){返回$this->mutateAttribute($key,$value);}//在此处修改您的值返回$value。'd';}[代码]它从未被调用,在IDE中它显示它已被覆盖。hasGetMutator不是自动调用的吗?只有当您尝试访问该属性时,才会调用mutator。例如,如果您执行
$model->my_attribute
,而实际数据库中没有
my_attribute
,则将调用
hasGetMutator
查找函数
getMyAttributeAttribute
。通过将自定义属性添加到模型中的
$appends
字段,您可以自动附加自定义属性,如果需要动态的话,您可以在构造函数中执行此操作。第一个选项对我来说很有吸引力。当您在发布上一次提交时出现间隙,我学到了很多:-)例如:Laravel集合现在是惰性的,在您访问/更新属性之前,它们不会调用访问器/变异器。
protected function __construct(array $attributes = [])
{
    parent::__construct($attributes);
    $this->casts = array_merge($this->casts, [
        'customCastColumn1' => MyCustomCast::class,
         // ...
    ]);
}