2017-09-20 09:48:19 2844次浏览 3条回答 0 悬赏 50 金钱

我们知道ActiveRecord有EVENT_BEFORE_INSERT、EVENT_AFTER_INSERT这些事件,但是这些事件是在哪里注册的呢?我指的是源码中哪里注册了这些事件,请问有人知道吗??

  • 回答于 2017-09-20 09:53 举报

    好像是在\vendor\yiisoft\yii2\db
    BaseActiveRecord.php 这个文件中

    3 条回复
    回复于 2017-09-20 10:34 回复

    并没有,这个文件中值看到这些事件名称常量的声明,和事件的触发,并没有看到时间的绑定。。

    回复于 2017-09-20 13:32 回复

    那根据事件的触发往后面找呗,至于你说的时间的绑定没明白是什么意思

    回复于 2017-09-20 17:58 回复

    打错了,是 事件绑定

  • 回答于 2017-09-20 15:19 举报

    yii\db\baseActiveRecord

    public function afterSave($insert, $changedAttributes)
        {
            $this->trigger($insert ? self::EVENT_AFTER_INSERT : self::EVENT_AFTER_UPDATE, new AfterSaveEvent([
                'changedAttributes' => $changedAttributes
            ]));
        }
    

    调用

    protected function updateInternal($attributes = null)
        {
            if (!$this->beforeSave(false)) {
                return false;
            }
            $values = $this->getDirtyAttributes($attributes);
            if (empty($values)) {
                $this->afterSave(false, $values);
                return 0;
            }
            $condition = $this->getOldPrimaryKey(true);
            $lock = $this->optimisticLock();
            if ($lock !== null) {
                $values[$lock] = $this->$lock + 1;
                $condition[$lock] = $this->$lock;
            }
            // We do not check the return value of updateAll() because it's possible
            // that the UPDATE statement doesn't change anything and thus returns 0.
            $rows = static::updateAll($values, $condition);
    
            if ($lock !== null && !$rows) {
                throw new StaleObjectException('The object being updated is outdated.');
            }
    
            if (isset($values[$lock])) {
                $this->$lock = $values[$lock];
            }
    
            $changedAttributes = [];
            foreach ($values as $name => $value) {
                $changedAttributes[$name] = isset($this->_oldAttributes[$name]) ? $this->_oldAttributes[$name] : null;
                $this->_oldAttributes[$name] = $value;
            }
            $this->afterSave(false, $changedAttributes);
    
            return $rows;
        }
    
    2 条回复
    回复于 2017-09-20 17:59 回复

    谢谢,我问的是这些事件绑定的地方,不是触发的地方,也就是类似:$this->on(self::EVENT_AFTER_INSERT, ...),不知道在哪里写 的

    回复于 2017-09-20 20:58 回复

    系统没有监听这个事件,系统提供这个触发这个事件,是给开发者监听的

  • 回答于 2017-09-22 16:00 举报

    文档这里不是有吗?
    企业微信截图_15060671788737.png

您需要登录后才可以回答。登录 | 立即注册
是啊俊
经理

是啊俊

注册时间:2017-07-28
最后登录:2018-01-23
在线时长:13小时58分
  • 粉丝0
  • 金钱785
  • 威望20
  • 积分1115

热门问题