0
我相信有更多的開發者需要使用區域日期格式(在應用程序前端顯示),而不是那些在瀏覽器中使用默認格式(12/22/2016。Laravel - 爲獲取者和創建者設置3個函數
所以我在我的Laravel項目標準日期像created_at,的updated_at和deleted_at做了一個小特點:
<?php
namespace App\Traits;
use Carbon\Carbon;
trait FormatDates
{
protected $localFormat = 'd.m.Y H:i';
// save the date in UTC format in DB table
public function setCreatedAtAttribute($date)
{
$this->attributes['created_at'] = Carbon::parse($date);
}
// convert the UTC format to local format
public function getCreatedAtAttribute($date)
{
return Carbon::parse($date)->format($this->localFormat);
}
// get diffForHumans for this attribute
public function getCreatedAtHumanAttribute()
{
return Carbon::parse($this->attributes['created_at'])->diffForHumans();
}
// save the date in UTC format in DB table
public function setUpdatedAtAttribute($date)
{
$this->attributes['updated_at'] = Carbon::parse($date);
}
// convert the UTC format to local format
public function getUpdatedAtAttribute($date)
{
return Carbon::parse($date)->format($this->localFormat);
}
// get diffForHumans for this attribute
public function getUpdatedAtHumanAttribute()
{
return Carbon::parse($this->attributes['updated_at'])->diffForHumans();
}
// save the date in UTC format in DB table
public function setPublishedAtAttribute($date)
{
$this->attributes['published_at'] = Carbon::parse($date);
}
// convert the UTC format to local format
public function getPublishedAtAttribute($date)
{
return Carbon::parse($date)->format($this->localFormat);
}
// get diffForHumans for this attribute
public function getPublishedAtHumanAttribute()
{
return Carbon::parse($this->attributes['published_at'])->diffForHumans();
}
// save the date in UTC format in DB table
public function setDeletedAtAttribute($date)
{
$this->attributes['deleted_at'] = Carbon::parse($date);
}
// convert the UTC format to local format
public function getDeletedAtAttribute($date)
{
return Carbon::parse($date)->format($this->localFormat);
}
// get diffForHumans for this attribute
public function getDeletedAtHumanAttribute()
{
return Carbon::parse($this->attributes['deleted_at'])->diffForHumans();
}
}
有實際上只有3這些日期的功能,這些功能是:
set the date so it can be saved with date time picker
get the date in locale format (22.12.2016 14:39)
get the date in human readable format
所以我的問題是如何使這個特質只有3個功能,而不是所有的時間重複它的每一個變量?這是可行的嗎?
因此,你所說的是,如果我把它留在可讀性方面並沒有那麼差,即使它是更多的代碼 – lewis4u
當然,意見各不相同,但上面的代碼是自解釋性和高度可讀的,即使它涉及重複的代碼。當模型中的可用日期字段變化很大時,您可能需要考慮使用自定義__get/__ set解決方案,從而根據模型getDates()的輸出使該特性更具動態性。如果日期字段在整個模型中相對統一,我個人認爲目前的解決方案沒有太多錯誤。 – Robert