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

时间:2013-10-22 16:15:41

标签: events cakephp behavior dispatchevent

由于我的应用程序是如何构建的,我需要为beforeSaveAssociatedafterSaveAssociated创建事件处理程序。为了实现这一点,我更新了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(内置事件),它确实有效,所以据我所知,这不是一个没有正确附加行为的问题。

非常感谢任何帮助,

2 个答案:

答案 0 :(得分:3)

我认为这是因为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 :(得分:0)

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