3 關注者

類別 yii\behaviors\TimestampBehavior

繼承yii\behaviors\TimestampBehavior » yii\behaviors\AttributeBehavior » yii\base\Behavior » yii\base\BaseObject
實作yii\base\Configurable
版本可用性2.0
原始碼 https://github.com/yiisoft/yii2/blob/master/framework/behaviors/TimestampBehavior.php

TimestampBehavior 會自動將指定屬性填入目前時間戳記。

若要使用 TimestampBehavior,請將以下程式碼插入您的 ActiveRecord 類別

use yii\behaviors\TimestampBehavior;

public function behaviors()
{
    return [
        TimestampBehavior::class,
    ];
}

預設情況下,當相關聯的 AR 物件正在插入時,TimestampBehavior 會將 `created_at` 和 `updated_at` 屬性填入目前時間戳記;當 AR 物件正在更新時,它會將 `updated_at` 屬性填入時間戳記。時間戳記值由 `time()` 取得。

因為屬性值將由此行為自動設定,它們通常不是使用者輸入,因此不應被驗證,亦即 `created_at` 和 `updated_at` 不應出現在模型的 rules() 方法中。

為了使上述實作能與 MySQL 資料庫搭配運作,請將欄位 (`created_at`, `updated_at`) 宣告為 int(11) 以作為 UNIX 時間戳記。

如果您的屬性名稱不同,或者您想使用不同的方式計算時間戳記,您可以設定 $createdAtAttribute$updatedAtAttribute$value 屬性,如下所示

use yii\db\Expression;

public function behaviors()
{
    return [
        [
            'class' => TimestampBehavior::class,
            'createdAtAttribute' => 'create_time',
            'updatedAtAttribute' => 'update_time',
            'value' => new Expression('NOW()'),
        ],
    ];
}

如果您使用如上述範例中的 yii\db\Expression 物件,則屬性將不會保留時間戳記值,而是在記錄儲存後保留 Expression 物件本身。如果您之後需要從資料庫取得該值,您應該呼叫記錄的 refresh() 方法。

TimestampBehavior 也提供一個名為 touch() 的方法,讓您可以將目前時間戳記指派給指定的屬性,並將它們儲存到資料庫。例如:

$model->touch('creation_time');

公開屬性

隱藏繼承的屬性

屬性 類型 描述 定義於
$attributes array 要自動填入值的屬性列表,值由 $value 指定。 yii\behaviors\AttributeBehavior
$createdAtAttribute string 將接收時間戳記值的屬性。如果您不想記錄建立時間,請將此屬性設為 false。 yii\behaviors\TimestampBehavior
$owner yii\base\Component|null 此行為的擁有者 yii\base\Behavior
$preserveNonEmptyValues boolean 是否保留非空的屬性值。 yii\behaviors\AttributeBehavior
$skipUpdateOnClean boolean $owner 未被修改時,是否跳過此行為 yii\behaviors\AttributeBehavior
$updatedAtAttribute string 將接收時間戳記值的屬性。 yii\behaviors\TimestampBehavior
$value mixed 將指派給目前屬性的值。 yii\behaviors\TimestampBehavior

公開方法

隱藏繼承的方法

方法 描述 定義於
__call() 呼叫指定的非類別方法。 yii\base\BaseObject
__construct() 建構子。 yii\base\BaseObject
__get() 傳回物件屬性的值。 yii\base\BaseObject
__isset() 檢查屬性是否已設定,即已定義且非 null。 yii\base\BaseObject
__set() 設定物件屬性的值。 yii\base\BaseObject
__unset() 將物件屬性設定為 null。 yii\base\BaseObject
attach() 將行為物件附加到元件。 yii\base\Behavior
canGetProperty() 返回一個值,指示屬性是否可以被讀取。 yii\base\BaseObject
canSetProperty() 返回一個值,指示屬性是否可以被設定。 yii\base\BaseObject
className() 返回此類別的完整限定名稱。 yii\base\BaseObject
detach() 從組件中分離行為物件。 yii\base\Behavior
evaluateAttributes() 評估屬性值並將其指派給目前的屬性。 yii\behaviors\AttributeBehavior
events() $owner 的事件宣告事件處理器。 yii\behaviors\AttributeBehavior
hasMethod() 返回一個值,指示方法是否已定義。 yii\base\BaseObject
hasProperty() 返回一個值,指示屬性是否已定義。 yii\base\BaseObject
init() 初始化物件。 yii\behaviors\TimestampBehavior
touch() 將時間戳記屬性更新為目前的時間戳記。 yii\behaviors\TimestampBehavior

受保護的方法

隱藏繼承的方法

方法 描述 定義於
getValue() 返回目前屬性的值。 yii\behaviors\TimestampBehavior

屬性詳細資訊

隱藏繼承的屬性

$createdAtAttribute 公開屬性

將接收時間戳記值的屬性。如果您不想記錄建立時間,請將此屬性設為 false。

public string $createdAtAttribute 'created_at'
$updatedAtAttribute 公開屬性

將接收時間戳記值的屬性。如果您不想要記錄更新時間,請將此屬性設定為 false。

public string $updatedAtAttribute 'updated_at'
$value 公開屬性

在值為 null 的情況下,PHP 函數 time() 的結果將被用作值。

將指派給目前屬性的值。這可以是匿名函數、陣列格式的可調用物件 (例如 [$this, 'methodName'])、代表資料庫運算式的 Expression 物件 (例如 new Expression('NOW()'))、純量、字串或任意值。如果是前者,則函數的回傳值將被指派給屬性。函數的簽章應如下:

function ($event)
{
    // return value will be assigned to the attribute
}
public mixed $value null

方法詳細資訊

隱藏繼承的方法

__call() 公開方法

定義於: yii\base\BaseObject::__call()

呼叫指定的非類別方法。

請勿直接調用此方法,因為它是一個 PHP 魔術方法,當調用未知方法時會被隱式調用。

public mixed __call ( $name, $params )
$name string

方法名稱

$params array

方法參數

return mixed

方法回傳值

throws yii\base\UnknownMethodException

當調用未知方法時

                public function __call($name, $params)
{
    throw new UnknownMethodException('Calling unknown method: ' . get_class($this) . "::$name()");
}

            
__construct() 公開方法

定義於: yii\base\BaseObject::__construct()

建構子。

預設實作會執行兩件事

  • 使用給定的配置 $config 初始化物件。
  • 調用 init()

如果在子類別中覆寫此方法,建議

  • 建構子的最後一個參數是一個配置陣列,就像此處的 $config 一樣。
  • 在建構子的結尾調用父類別的實作。
public void __construct ( $config = [] )
$config array

將用於初始化物件屬性的名稱-值對。

                public function __construct($config = [])
{
    if (!empty($config)) {
        Yii::configure($this, $config);
    }
    $this->init();
}

            
__get() 公開方法

定義於: yii\base\BaseObject::__get()

傳回物件屬性的值。

請勿直接調用此方法,因為它是一個 PHP 魔術方法,當執行 $value = $object->property; 時會被隱式調用。

另請參閱 __set()

public mixed __get ( $name )
$name string

屬性名稱

return mixed

屬性值

throws yii\base\UnknownPropertyException

如果屬性未定義

throws yii\base\InvalidCallException

如果屬性是唯寫的

                public function __get($name)
{
    $getter = 'get' . $name;
    if (method_exists($this, $getter)) {
        return $this->$getter();
    } elseif (method_exists($this, 'set' . $name)) {
        throw new InvalidCallException('Getting write-only property: ' . get_class($this) . '::' . $name);
    }
    throw new UnknownPropertyException('Getting unknown property: ' . get_class($this) . '::' . $name);
}

            
__isset() 公開方法

定義於: yii\base\BaseObject::__isset()

檢查屬性是否已設定,即已定義且非 null。

請勿直接調用此方法,因為它是一個 PHP 魔術方法,當執行 isset($object->property) 時會被隱式調用。

請注意,如果屬性未定義,將會返回 false。

另請參閱 https://php.dev.org.tw/manual/en/function.isset.php

public boolean __isset ( $name )
$name string

屬性名稱或事件名稱

return boolean

指示具名屬性是否已設定 (非 null)。

                public function __isset($name)
{
    $getter = 'get' . $name;
    if (method_exists($this, $getter)) {
        return $this->$getter() !== null;
    }
    return false;
}

            
__set() 公開方法

定義於: yii\base\BaseObject::__set()

設定物件屬性的值。

請勿直接調用此方法,因為它是一個 PHP 魔術方法,當執行 $object->property = $value; 時會被隱式調用。

另請參閱 __get()

public void __set ( $name, $value )
$name string

屬性名稱或事件名稱

$value mixed

屬性值

throws yii\base\UnknownPropertyException

如果屬性未定義

throws yii\base\InvalidCallException

如果屬性是唯讀的

                public function __set($name, $value)
{
    $setter = 'set' . $name;
    if (method_exists($this, $setter)) {
        $this->$setter($value);
    } elseif (method_exists($this, 'get' . $name)) {
        throw new InvalidCallException('Setting read-only property: ' . get_class($this) . '::' . $name);
    } else {
        throw new UnknownPropertyException('Setting unknown property: ' . get_class($this) . '::' . $name);
    }
}

            
__unset() 公開方法

定義於: yii\base\BaseObject::__unset()

將物件屬性設定為 null。

請勿直接調用此方法,因為它是一個 PHP 魔術方法,當執行 unset($object->property) 時會被隱式調用。

請注意,如果屬性未定義,此方法將不會執行任何操作。如果屬性是唯讀的,它將會拋出例外。

另請參閱 https://php.dev.org.tw/manual/en/function.unset.php

public void __unset ( $name )
$name string

屬性名稱

throws yii\base\InvalidCallException

如果屬性是唯讀的。

                public function __unset($name)
{
    $setter = 'set' . $name;
    if (method_exists($this, $setter)) {
        $this->$setter(null);
    } elseif (method_exists($this, 'get' . $name)) {
        throw new InvalidCallException('Unsetting read-only property: ' . get_class($this) . '::' . $name);
    }
}

            
attach() 公開方法

定義於: yii\base\Behavior::attach()

將行為物件附加到元件。

預設實作將設定 $owner 屬性,並附加在 events() 中宣告的事件處理器。如果您覆寫此方法,請確保調用父類別的實作。

public void attach ( $owner )
$owner yii\base\Component

此行為將附加到的組件。

                public function attach($owner)
{
    $this->owner = $owner;
    foreach ($this->events() as $event => $handler) {
        $this->_attachedEvents[$event] = $handler;
        $owner->on($event, is_string($handler) ? [$this, $handler] : $handler);
    }
}

            
canGetProperty() 公開方法

定義於: yii\base\BaseObject::canGetProperty()

返回一個值,指示屬性是否可以被讀取。

如果屬性是可讀的

  • 類別具有與指定名稱關聯的 getter 方法 (在此情況下,屬性名稱不區分大小寫);
  • 類別具有與指定名稱的成員變數 (當 $checkVars 為 true 時);

另請參閱 canSetProperty()

public boolean canGetProperty ( $name, $checkVars true )
$name string

屬性名稱

$checkVars boolean

是否將成員變數視為屬性

return boolean

指示屬性是否可讀

                public function canGetProperty($name, $checkVars = true)
{
    return method_exists($this, 'get' . $name) || $checkVars && property_exists($this, $name);
}

            
canSetProperty() 公開方法

定義於: yii\base\BaseObject::canSetProperty()

返回一個值,指示屬性是否可以被設定。

如果屬性是可寫入的

  • 類別具有與指定名稱關聯的 setter 方法 (在此情況下,屬性名稱不區分大小寫);
  • 類別具有與指定名稱的成員變數 (當 $checkVars 為 true 時);

另請參閱 canGetProperty()

public boolean canSetProperty ( $name, $checkVars true )
$name string

屬性名稱

$checkVars boolean

是否將成員變數視為屬性

return boolean

指示屬性是否可寫入

                public function canSetProperty($name, $checkVars = true)
{
    return method_exists($this, 'set' . $name) || $checkVars && property_exists($this, $name);
}

            
className() 公開靜態方法
自 2.0.14 版本起已棄用。在 PHP >=5.5 上,請改用 ::class

定義於: yii\base\BaseObject::className()

返回此類別的完整限定名稱。

public static string className ( )
return string

此類別的完整限定名稱。

                public static function className()
{
    return get_called_class();
}

            
detach() 公開方法

定義於: yii\base\Behavior::detach()

從組件中分離行為物件。

預設實作將取消設定 $owner 屬性,並分離在 events() 中宣告的事件處理器。如果您覆寫此方法,請確保調用父類別的實作。

public void detach ( )

                public function detach()
{
    if ($this->owner) {
        foreach ($this->_attachedEvents as $event => $handler) {
            $this->owner->off($event, is_string($handler) ? [$this, $handler] : $handler);
        }
        $this->_attachedEvents = [];
        $this->owner = null;
    }
}

            
evaluateAttributes() 公開方法

定義於: yii\behaviors\AttributeBehavior::evaluateAttributes()

評估屬性值並將其指派給目前的屬性。

public void evaluateAttributes ( $event )
$event yii\base\Event

                public function evaluateAttributes($event)
{
    if (
        $this->skipUpdateOnClean
        && $event->name == ActiveRecord::EVENT_BEFORE_UPDATE
        && empty($this->owner->dirtyAttributes)
    ) {
        return;
    }
    if (!empty($this->attributes[$event->name])) {
        $attributes = (array) $this->attributes[$event->name];
        $value = $this->getValue($event);
        foreach ($attributes as $attribute) {
            // ignore attribute names which are not string (e.g. when set by TimestampBehavior::updatedAtAttribute)
            if (is_string($attribute)) {
                if ($this->preserveNonEmptyValues && !empty($this->owner->$attribute)) {
                    continue;
                }
                $this->owner->$attribute = $value;
            }
        }
    }
}

            
events() 公開方法

定義於: yii\behaviors\AttributeBehavior::events()

$owner 的事件宣告事件處理器。

子類別可以覆寫此方法,以宣告應將哪些 PHP 回調附加到 $owner 組件的事件。

當行為附加到擁有者時,回調將附加到 $owner 的事件;當行為從組件分離時,它們將從事件中分離。

回調可以是以下任何一種

  • 此行為中的方法:'handleClick',等同於 [$this, 'handleClick']
  • 物件方法:[$object, 'handleClick']
  • 靜態方法:['Page', 'handleClick']
  • 匿名函數:function ($event) { ... }

以下是一個範例

[
    Model::EVENT_BEFORE_VALIDATE => 'myBeforeValidate',
    Model::EVENT_AFTER_VALIDATE => 'myAfterValidate',
]
public array events ( )
return array

事件 (陣列鍵) 和對應的事件處理器方法 (陣列值)。

                public function events()
{
    return array_fill_keys(
        array_keys($this->attributes),
        'evaluateAttributes'
    );
}

            
getValue() 受保護的方法

返回目前屬性的值。

$valuenull 的情況下,PHP 函數 time() 的結果將被用作值。

此方法由 evaluateAttributes() 調用。其回傳值將被指派給與觸發事件對應的屬性。

protected mixed getValue ( $event )
$event yii\base\Event

觸發目前屬性更新的事件。

return mixed

屬性值

                protected function getValue($event)
{
    if ($this->value === null) {
        return time();
    }
    return parent::getValue($event);
}

            
hasMethod() 公開方法

定義於: yii\base\BaseObject::hasMethod()

返回一個值,指示方法是否已定義。

預設實作是對 php 函數 method_exists() 的調用。當您實作 php 魔術方法 __call() 時,您可以覆寫此方法。

public boolean hasMethod ( $name )
$name string

方法名稱

return boolean

指示方法是否已定義

                public function hasMethod($name)
{
    return method_exists($this, $name);
}

            
hasProperty() 公開方法

定義於: yii\base\BaseObject::hasProperty()

返回一個值,指示屬性是否已定義。

如果屬性已定義

  • 類別具有與指定名稱關聯的 getter 或 setter 方法 (在此情況下,屬性名稱不區分大小寫);
  • 類別具有與指定名稱的成員變數 (當 $checkVars 為 true 時);

另請參閱

public boolean hasProperty ( $name, $checkVars true )
$name string

屬性名稱

$checkVars boolean

是否將成員變數視為屬性

return boolean

指示屬性是否已定義

                public function hasProperty($name, $checkVars = true)
{
    return $this->canGetProperty($name, $checkVars) || $this->canSetProperty($name, false);
}

            
init() 公開方法

初始化物件。

在使用給定配置初始化物件後,此方法會在建構子的結尾被調用。

public void init ( )

                public function init()
{
    parent::init();
    if (empty($this->attributes)) {
        $this->attributes = [
            BaseActiveRecord::EVENT_BEFORE_INSERT => [$this->createdAtAttribute, $this->updatedAtAttribute],
            BaseActiveRecord::EVENT_BEFORE_UPDATE => $this->updatedAtAttribute,
        ];
    }
}

            
touch() 公開方法

將時間戳記屬性更新為目前的時間戳記。

$model->touch('lastVisit');
public void touch ( $attribute )
$attribute string

要更新的屬性名稱。

throws yii\base\InvalidCallException

如果擁有者是新記錄 (自 2.0.6 版本起)。

                public function touch($attribute)
{
    /* @var $owner BaseActiveRecord */
    $owner = $this->owner;
    if ($owner->getIsNewRecord()) {
        throw new InvalidCallException('Updating the timestamp is not possible on a new record.');
    }
    $owner->updateAttributes(array_fill_keys((array) $attribute, $this->getValue(null)));
}