Events CakePHP 3事件
如果某个特定的find方法在我的Contacts表上有返回值,我想在我的Notifications表中创建一个条目 所以在ContactsTable中,我创建了一个事件Events CakePHP 3事件,events,cakephp-3.0,Events,Cakephp 3.0,如果某个特定的find方法在我的Contacts表上有返回值,我想在我的Notifications表中创建一个条目 所以在ContactsTable中,我创建了一个事件 use Cake\Event\Event; public function checkDuplicates() { //... some code here $event = new Event('Model.Contacts.afterDuplicatesCheck', $this, [
use Cake\Event\Event;
public function checkDuplicates()
{
//... some code here
$event = new Event('Model.Contacts.afterDuplicatesCheck', $this, [
'duplicates' => $duplicates
]);
$this->eventManager()->dispatch($event);
}
我已经在/src/Event创建了ContactsListener.php
namespace App\Event;
use Cake\Event\Event;
use Cake\Event\EventListenerInterface;
use Cake\Log\Log;
class ContactsListener implements EventListenerInterface
{
public function implementedEvents()
{
return [
'Model.Contacts.afterDuplicatesCheck' => 'createNotificationAfterCheckDuplicates',
];
}
public function createNotificationAfterCheckDuplicates(Event $event, array $duplicates)
{
Log::debug('Here I am');
}
}
在我的NotificationsTable.php中,我有以下代码
public function initialize(array $config)
{
$this->table('notifications');
$this->displayField('id');
$this->primaryKey('id');
$listener = new ContactsListener();
$this->eventManager()->on($listener);
}
我想这部分就是问题所在,因为我从未得到日志条目。烹饪书对此不够清楚,我发现的所有代码都与烹饪书描述的不一样,即使是蛋糕3
我应该如何以及在何处连接侦听器?您使用的是两个单独的本地事件管理器实例,它们将永远不会收到对方的消息。您必须在您的
ContactsTable
实例上明确订阅管理器,或者使用全局事件管理器来获得所有事件的通知:
[……]
每个模型都有一个单独的事件管理器,而视图和控制器共享一个。这允许模型事件自包含,并允许组件或控制器在必要时对视图中创建的事件进行操作
全球活动经理
除了实例级事件管理器之外,CakePHP还提供了一个全局事件管理器,允许您侦听应用程序中触发的任何事件
[……]
所以,要么像这样做
\Cake\ORM\TableRegistry::get('Contacts')->eventManager()->on($listener);
只有在清除注册表或全局订阅之前,它才会工作
\Cake\Event\EventManager::instance()->on($listener);
附带说明
为了让它工作,您的NotificationsTable
类必须在某个地方实例化。因此,我建议将其封装在utitlity类或组件中,该类或组件将侦听事件,并使用NotificationsTable
保存通知