laravel - 在 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.
如果我们可以避免评估,请!
解决方案
通过在模型中执行以下操作,您可能会取得一些有限的成功:
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,
// ...
]);
}
这将在模型构建时将所需的演员表添加到模型中。
推荐阅读
- ios - 为什么快速跳转到另一个页面时会出现意外空间
- google-drive-api - 通过 Salesforce 在谷歌驱动器中上传大文件(最后一个块)时无法获得响应 200
- github - GIT HELP:主分支为空且不活动
- android - WebView 更改音频输出设备
- .net - MS Teams 应用程序:访问此应用程序时出现问题
- amazon-web-services - 资源必须采用 ARN 格式或“*”
- php - 如何解决 PHP 7.4.5、XAMPP 3.2.4、Windows 10 x64 中的“调用未定义函数...”问题?
- python - python类中的默认参数值
- c# - C# 将列表从 json 传递到 viev,并显示在一个文本框中
- deployment - 如何查看 localhost 中部署的整个以太坊区块链?