CakePHP:在行为中触发自定义事件

问题描述 投票:0回答:2

由于我的应用程序的构建方式,我需要为

beforeSaveAssociated
afterSaveAssociated
创建事件处理程序。为此,我更新了 AppModel.php 以包含以下相关代码:

public function saveAssociated(array $data = null, array $options = array()) {
    $this->after_save_options = NULL;

    $event = new CakeEvent('Model.beforeSaveAssociated', $this, array(&$data, &$options));
    $this->after_save_options = NULL;
    $this->getEventManager()->dispatch($event);

    if (parent::saveAssociated($data, $options)) {
        if (is_array($this->after_save_options)) {
            $curData = $this->data;
            $this->data = $this->_tempData;
            $event = new CakeEvent('Model.afterSaveAssociated', $this, $this->after_save_options);
            $this->after_save_options = NULL;
            $this->getEventManager()->dispatch($event);
            $this->data = $curData;
        }
        if ($this->_tempData) {
            $this->_tempData = FALSE;
        }
        return TRUE;
    }
    return FALSE;
}

public function implementedEvents() {
    return array_merge(parent::implementedEvents(), array(
        'Model.beforeSaveAssociated' => array(
            'callable' => 'beforeSaveAssociated',
            'passParams' => TRUE,
        ),
        'Model.afterSaveAssociated' => array(
            'callable' => 'afterSaveAssociated',
            'passParams' => TRUE,
        ),
    ));
}

尽管这对于模型类中定义的任何

beforeSaveAssociated
都适用,但每当我在行为中定义它时,它都不会被触发。如果我更新上面的
saveAssociated
来触发
Model.beforeSave
(内置事件),它确实有效,所以据我所知,这不是行为未正确附加的问题。

非常感谢任何帮助,

php events cakephp behavior dispatchevent
2个回答
4
投票

我认为这是因为BehaviorCollection只是监听这些事件(取自课堂):

public function implementedEvents() {
    return array(
        'Model.beforeFind' => 'trigger',
        'Model.afterFind' => 'trigger',
        'Model.beforeValidate' => 'trigger',
        'Model.afterValidate' => 'trigger',
        'Model.beforeSave' => 'trigger',
        'Model.afterSave' => 'trigger',
        'Model.beforeDelete' => 'trigger',
        'Model.afterDelete' => 'trigger'
    );
}

不是行为监听事件,而是集合并触发行为。如果不查的话,不能 100% 确定这一点,但我认为这就是它的工作原理。

你可以尝试做的是让需要接收这些事件的行为直接监听事件。


1
投票

我认为这个问题是因为行为扩展了 ModelBehavior 并且这些类不知道您在 AppModel 中创建的新方法

© www.soinside.com 2019 - 2024. All rights reserved.