sha*_*swa 5 php traits mutators laravel laravel-5
我有一个日期字段列表,所有这些字段在mutator中都有相同的逻辑.我想将这个功能提取到一个特征,以便将来我需要的是在模型中创建一个日期字段数组并使用特征.
像这样的东西:
foreach( $dates as $date ) {
$dateCamelCase = $this->dashesToUpperCase($date);
$setDateFunctionName ='set'.$dateCamelCase.'Attribute';
$this->{$setDateFunctionName} = function() use($date) {
$this->attributes[$date] = date( 'Y-m-d', strtotime( $date ));
};
}
Run Code Online (Sandbox Code Playgroud)
sep*_*ehr 11
在回答您的具体问题之前,让我们先看看 Eloquent mutators 是如何工作的。
所有 EloquentModel派生类都有它们的__set()和offsetSet()方法来调用setAttribute负责设置属性值并在需要时改变它的方法。
在设置值之前,它会检查:
通过理解这一点,我们可以简单地进入流程并使用我们自己的自定义逻辑对其进行重载。这是一个实现:
<?php
namespace App\Models\Concerns;
use Illuminate\Database\Eloquent\Concerns\HasAttributes;
trait MutatesDatesOrWhatever
{
public function setAttribute($key, $value)
{
// Custom mutation logic goes here before falling back to framework's
// implementation.
//
// In your case, you need to check for date fields and mutate them
// as you wish. I assume you have put your date field names in the
// `$dates` model property and so we can utilize Laravel's own
// `isDateAttribute()` method here.
//
if ($value && $this->isDateAttribute($key)) {
$value = date('Y-m-d', strtotime($value));
}
// Handover the rest to Laravel's own setAttribute(), so that other
// mutators will remain intact...
return parent::setAttribute($key, $value);
}
}
Run Code Online (Sandbox Code Playgroud)
不用说,您的模型需要使用此特征来启用该功能。
如果变异日期是您需要具有“动态命名的变异器”的唯一用例,则根本不需要。您可能已经注意到,Laravel 本身可以重新格式化 Eloquent 的日期字段:
class Whatever extends Model
{
protected $dates = [
'date_field_1',
'date_field_2',
// ...
];
protected $dateFormat = 'Y-m-d';
}
Run Code Online (Sandbox Code Playgroud)
此处列出的所有字段都将按照 进行格式化$dateFormat。那我们就不要重新发明轮子了。
| 归档时间: |
|
| 查看次数: |
1267 次 |
| 最近记录: |