首页 > 解决方案 > 在 Laravel 模型类中动态添加访问器方法

问题描述

我已经构建了函数名称,但是我希望在一个本质上是动态的数组中,这意味着它们可以是 2 或 10,如下所示:

在此处输入图像描述

结果

我希望他们像这样驻留在模型类(例如:用户)中:

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.

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

标签: laravel

解决方案


通过在模型中执行以下操作,您可能会取得一些有限的成功:

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

这样做是覆盖hasGetMutator通常只检查函数是否'get'.Str::studly($key).'Attribute'存在于类中的方法,如果该函数名称存在于您的数组中也返回 true,并且还修改mutateAttribute函数以执行您的自定义突变(除了执行默认突变) .

但是,如果您的突变是标准突变,那么我建议您改用自定义演员表:

<?php

namespace App\Casts;

use Illuminate\Contracts\Database\Eloquent\CastsAttributes;

class MyCustomCast implements CastsAttributes
{

    public function get($model, $key, $value, $attributes) {
        // Do the cast
        return $value;
    }

    //Optional
    public function set($model, $key, $value, $attributes)
    {
        // Reverse the cast 
        return $value;
    }
}

要使其适用于动态属性,您可以将其添加到模型中:

protected function __construct(array $attributes = [])
{
    parent::__construct($attributes);
    $this->casts = array_merge($this->casts, [
        'customCastColumn1' => MyCustomCast::class,
         // ...
    ]);
}

这将在模型构建时将所需的演员表添加到模型中。


推荐阅读