0

由于我的应用程序是如何构建的,我需要为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(内置事件),它确实有效,据我所知,这不是行为未正确附加的问题。

任何帮助是极大的赞赏,

4

2 回答 2

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% 确定,但我认为这就是它的工作原理。

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

于 2013-10-22T16:55:08.790 回答
0

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

于 2013-10-22T16:28:52.960 回答