yii2 module类的behavior函数

来源:互联网 发布:拳皇咆哮 源码 编辑:程序博客网 时间:2024/05/16 06:36

之前已经说过了,函数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

0 0