yii2 module類的behavior函數

之前已經說過了,函數behaviors在controller類中起的作用是進行攔截器的作用,而在Module中也是一樣的

在yii2給出的例子是這樣的:

 /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            TimestampBehavior::className(),
        ];
    }

而TimestampBehavior類是這樣的

class TimestampBehavior extends AttributeBehavior
{
    public $createdAtAttribute = 'created_at';
    public $updatedAtAttribute = 'updated_at';
    public $value;


    /**
     * @inheritdoc
     */
    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,
            ];
        }
    }

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

    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)));
    }
}
類TimestampBehavior是集成自AttributeBehavior,也就是說該攔截器主要作用時,當我們進行修改類的屬性的時候觸發的,而觸發動作主要定義在函數 init當中的。

init函數需要填充一個數組該數組的每個元素都定義了一件事,就是當有INSERT數據庫操作的時候,需要修改的類的屬性的時候是 create_at 和update_at

當有UPDATE數據庫操作的時候,需要重新修改的類的屬性是update_at

實現的主要功能是函數init   和函數getValue

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章