5
目前我已将用户时区保存在他们的数据库行中,并且每次打印日期时都会将其转换为用户的时区。我怎样才能以干的方式做到这一点?在Laravel 4中更改用户时区的最佳方法是什么?
我应该重写Eloquent返回Carbon DateTime对象的位置吗?如果是这样,我应该把它放在下面的特征中,所以我只需要写一次呢?
<?php
use Carbon\Carbon;
use Illuminate\Database\Eloquent;
trait ConvertTimeZone {
/**
* Return a timestamp as DateTime object.
*
* @param mixed $value
* @return DateTime
*/
protected function asDateTime($value)
{
// If this value is an integer, we will assume it is a UNIX timestamp's value
// and format a Carbon object from this timestamp. This allows flexibility
// when defining your date fields as they might be UNIX timestamps here.
if (is_numeric($value))
{
return Carbon::createFromTimestamp($value);
}
// If the value is in simply year, month, day format, we will instantiate the
// Carbon instances from that fomrat. Again, this provides for simple date
// fields on the database, while still supporting Carbonized conversion.
elseif (preg_match('/^(\d{4})-(\d{2})-(\d{2})$/', $value))
{
return Carbon::createFromFormat('Y-m-d', $value);
}
// Finally, we will just assume this date is in the format used by default on
// the database connection and use that format to create the Carbon object
// that is returned back out to the developers after we convert it here.
elseif (! $value instanceof DateTime)
{
$format = $this->getDateFormat();
$timezone = \Auth::user()->timezone;
return Carbon::createFromFormat($format, $value, $timezone);
}
return Carbon::instance($value);
}
}
请您为什么延伸的BaseModel比使用性状最好告诉我?谢谢 –
这不是更好,特质的东西其实是相当不错的,而且工作原理也一样。自从我开始与Laravel合作以来,这就是我一直在做的事情,我想我可以分享它。当然,这样做的唯一好处是它不需要PHP 5.4.0,但这可能不是一个主要问题。 – rmobis
只是使用增变器可能会更好。 –