CakePHP 3.x事件系统 [英] CakePHP 3.x Event System

查看:170
本文介绍了CakePHP 3.x事件系统的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道为什么在我的模型中的afterSave事件没有被触发。看起来当我在表的initialize方法中运行save方法时,不会触发afterSave事件。

I can't figure out why the afterSave event in my model is not being triggered. It seems that when I run the save method within the initialize method of the table, the afterSave event isn't triggered.

在我的表类中:

public function initialize(array $config) {
    parent::initialize($config);
    ....
    $this->save($test);
}

public function afterSave($event, $entity, $options) {
    Log::debug('yay the event fired.');
}

项目已保存 - 我已检查过 - 实现任何阻止事件传播的东西。我测试了afterSave事件设置正确,因为当我保存在初始化方法外 - 从控制器 - 它工作正常。在2.x这将工作正常。

The item is saved - I've checked that - and I've not implemented anything that would stop the event from propagating. I've tested that the afterSave event is set up correctly because when I save outside of the initialize method - from the controller - it works fine. In 2.x this would have worked fine.

我会承认,即使我已经阅读了整个事件系统的书,有些我还没有完全掌握它,所以我可能缺少某些内容?

I will admit that even though I've read the whole book on the event system and some I still don't have a complete grasp of it, so I'm probably missing something?

感谢。

推荐答案

源代码在这种情况下通常有帮助。

A look at the source code often helps in such cases.

public function __construct(array $config = [])
{
    // ...

    $this->initialize($config);
    $this->_eventManager->on($this);

    // ...
}

https://github.com/cakephp /cakephp/blob/3.2.0/src/ORM/Table.php#L282-L283

https://github.com/cakephp/cakephp/blob/3.2.0/src/ORM/Table.php#L282-L283

如您所见, code> initialize 方法在表被注册为事件侦听器之前被调用,因此您的事件回调未被调用。

As you can see, the initialize method is invoked before the table is being registered as an event listener, and therefore your event callback is not being invoked.

所以要实现你想要做的,即保存一些东西,当一个模型被实例化/初始化和调用模型回调,你可以使用构造函数,或 Model.initialize 事件侦听器。

So to achieve what you're trying to do there, ie save something when a model is being instantiated/initialized and have the model callbacks invoked, you could use the constructor, or a Model.initialize event listener.

这篇关于CakePHP 3.x事件系统的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆