jc-it/yii2-datetime-behavior

通过魔术获取器和设置器处理日期/时间/时间戳字段的对象。

v0.1.0 2019-06-03 18:00 UTC

This package is auto-updated.

Last update: 2024-08-29 05:06:53 UTC


README

此扩展提供了一个包,用于帮助在(通常是)Active Record对象中处理日期/时间对象。

它提供魔术获取器和设置器来处理DateTime对象,而不是必须处理字符串。它是通过代理来实现的,以保持规则(即)在标准属性上工作。

$ composer require jc-it/yii2-datetime-behavior

或者

"jc-it/yii2-datetime-behavior": "^<latest version>"

将以下内容添加到您的 composer.json 文件的 require 部分。

配置

在模型中

/**
 * @return array
 */
public function behaviors(): array
{
    return ArrayHelper::merge(
        parent::behaviors(),
        [
            DateTimeBehavior::class => [
                'class' => DateTimeBehavior::class
            ],
        ]
    );
}

对于Active Record模型,它将自动检测日期/时间/datetime/时间戳字段并将行为应用于它们。

完整的配置

/**
 * @return array
 */
public function behaviors(): array
{
    return ArrayHelper::merge(
        parent::behaviors(),
        [
            DateTimeBehavior::class => [
                'class' => DateTimeBehavior::class,
                'attributes' => [ // Map of attribute to type.
                    'date_attribute' => DateTimeBehavior::TYPE_DATE,
                    'datetime_attribute' => DateTimeBehavior::TYPE_DATETIME,
                    'time_attribute' => DateTimeBehavior::TYPE_TIME,
                ],
                'attributeSuffix' => 'Object', // Suffix that will be used to detect if the behavior must be triggered.
                'attributeTimezone' => 'UTC', //When storing datetime values in timestamp fields this should default timezone of your database.
                'dateTimeClass' => Carbon::class, //The class of the datetime objects to be returned. Must extend from Carbon.
            ],
        ]
    );
}

用法

如果使用后缀访问受行为影响的功能,则将返回配置类的对象。

// Event has attribute from and until which are timestamps in the database
// Assuming in timezone Europe/Amsterdam

$event = Event::find()->one();
var_dump($event->from);
var_dump($event->fromObject);

// Will output

string '2019-01-01 12:00:00' (length=19)

object(Carbon\Carbon)
  public 'date' => string '2019-01-01 13:00:00.000000' (length=26)
  public 'timezone_type' => int 3
  public 'timezone' => string 'Europe/Amsterdam' (length=16)

鸣谢

许可证

MIT许可证(MIT)。有关更多信息,请参阅LICENSE