gpt4 book ai didi

events - CakePHP 3 事件

转载 作者:行者123 更新时间:2023-12-05 00:58:51 25 4
gpt4 key购买 nike

如果特定的查找方法在我的联系人表上有返回值,我想在我的通知表中创建一个条目。

所以在 ContactsTable 我创建了一个事件。

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 上的经理。实例,或使用获取所有事件通知的全局事件管理器:

[...]

Each model has a separate event manager, while the View and Controller share one. This allows model events to be self contained, and allow components or controllers to act upon events created in the view if necessary.

Global Event Manager

In addition to instance level event managers, CakePHP provides a global event manager that allows you to listen to any event fired in an application.

[...]



Cookbook > Events System > Accessing Event Managers

所以,要么做类似的事情
\Cake\ORM\TableRegistry::get('Contacts')->eventManager()->on($listener);

这只会在注册表被清除或全局订阅之前有效
\Cake\Event\EventManager::instance()->on($listener);

附注

为了让这一切正常工作,您的 NotificationsTable类必须在某处实例化。因此,我建议将其包装在一个实用程序类中,或者可能是一个组件中,它将监听事件,并使用 NotificationsTable保存通知。

关于events - CakePHP 3 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31566745/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com