CakePHP添加事件侦听器
我正在努力使CakePHP(v3.x)事件中的最后一个链接正常工作。在我的控制器CakePHP添加事件侦听器,php,cakephp,cakephp-3.0,Php,Cakephp,Cakephp 3.0,我正在努力使CakePHP(v3.x)事件中的最后一个链接正常工作。在我的控制器add方法中,我有公共函数 add() { $event = new Event('Model.Comment.created', $this, [ 'comment' => $comment ]); $this->eventManager()->dispatch($event); } 并设置我的listener类: namespace
add
方法中,我有公共函数
add()
{
$event = new Event('Model.Comment.created', $this, [
'comment' => $comment
]);
$this->eventManager()->dispatch($event);
}
并设置我的listener类:
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
类存在时 我也有同样的问题,然后我发现了这篇帖子:
它确实为我澄清了问题,并描述了您需要的最后一个链接步骤。假设您的Listener类位于应用程序的src
下的Event
文件夹中,您只需执行本文中的第4步,我已将他们的代码示例改编为您的示例:
最后,我们必须注册这个侦听器。为此,我们将使用全球可用的EventManager。将以下代码放在config/bootstrap.php的末尾
以上是一个全局侦听器。还可以按照CakePhp文档()在模型或控制器+视图层上注册事件。它在两行之间建议您可以在所需的层上注册侦听器-因此可能是beforeFilter
回调或initialize
方法上的AppController
,尽管我只测试了beforeFilter
回调
从CakePHP 3.0.0开始更新并转发
函数attach()
现在已被弃用。替换函数称为on()
,因此代码应如下所示:
use App\Event\CommentListener;
use Cake\Event\EventManager;
$CommentListener = new CommentListener();
EventManager::instance()->on($CommentListener); // REPLACED 'attach' here with 'on'
它是否显示了一些错误或警告?不,运行,但我知道它没有做任何事情,我知道我缺少了将两者联系在一起的部分,我不确定它是如何实现的。查看文档:我不清楚这些行的位置://将UserStatistic对象附加到订单的事件管理器$statistics=new UserStatistic()$此->订单->事件管理器()->on($statistics);
use App\Event\CommentListener;
use Cake\Event\EventManager;
$CommentListener = new CommentListener();
EventManager::instance()->on($CommentListener); // REPLACED 'attach' here with 'on'