2016-09-06 187 views
1

我正在努力获取CakePHP(v3.x)事件工作中的最终链接。在我的Controler add方法我有公共职能CakePHP添加事件监听器

add() 
{ 
     $event = new Event('Model.Comment.created', $this, [ 
      'comment' => $comment 
     ]); 
     $this->eventManager()->dispatch($event); 
} 

,并有我的监听器类设置:

namespace App\Event; 

use Cake\Log\Log; 
use Cake\Event\EventListener; 

class CommentListener implements EventListener { 

public function implementedEvents() { 
    return array(
     'Model.Comment.created' => 'updatePostLog', 
    ); 
} 

public function updatePostLog($event, $entity, $options) { 
    Log::write(
    'info', 
    'A new comment was published with id: ' . $event->data['id']); 
} 
} 

,但不能得到听者设置正确,特别是与我的应用程序知道我CommentListener类存在。

+0

它是否显示一些错误或警告? –

+0

不,运行,但我没有做任何事情,我知道我错过了将两者联系在一起的那一点,我不确定它是如何实现的。 –

+0

看文档: http://book.cakephp.org/3.0/en/core-libraries/events.html#registering-listeners 我很困惑这些行的去向: //附加UserStatistic对象订单的活动经理 $ statistics = new UserStatistic(); $ this-> Orders-> eventManager() - > on($ statistics); –

回答

1

我有相同的问题,然后我发现这个职位: Events in CakePHP 3 – A 4 step HowTo

这真是茅塞顿开,我和介绍,你是需要这最后链接步骤。假设你的监听器类是Event文件夹中的应用程序的src下,所有你需要做的就是在文章中第4步,我已经适应他们的代码示例,以你的例子:

最后,我们必须要注册这个听众。为此,我们将使用全局可用的EventManager。将下面的代码在你的配置月底/ bootstrap.php中

use App\Event\CommentListener; 
use Cake\Event\EventManager; 

$CommentListener = new CommentListener(); 
EventManager::instance()->attach($CommentListener); 

以上是一个全球性的听众。根据CakePhp文档(CakePHP 3.x Events System),也可以在Model或Controller + Views层上注册事件。它建议在行之间,您可以在需要的层上注册监听器 - 尽管我只测试了beforeFilter回调函数,所以可能使用beforeFilter回调或initialize方法中的AppController

更新为3.0.0的CakePHP和转发

attach()现在已经弃用的功能。替换函数被称为on(),因此代码应如下所示:

use App\Event\CommentListener; 
use Cake\Event\EventManager; 

$CommentListener = new CommentListener(); 
EventManager::instance()->on($CommentListener); // REPLACED 'attach' here with 'on'