events - CakePHP 3 事件

标签 events cakephp-3.0

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

所以在 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/

相关文章:

ios - iOS 上的 Phonegap 触发自定义事件

CakePHP 3.0 使用 Cells 构建权限菜单

php - 将变量发送到函数而不是发送到函数更好吗?

python - 从许多网页中获取数据的最佳方式(线程/事件驱动)

jQuery:处理多个事件以获得最佳性能的最佳方法

events - 分布式系统: Keeping timestamp consistency between different nodes

php - 如何增加cakephp Auth组件 session 过期时间

php - CakePHP 3 - 数据库表与自身的关联

cakephp-3.0 - cakephp 3.x 级联删除不工作

javascript - 将事件对象作为参数传递时出错