注册事件侦听器的位置
我正在尝试在 CakePHP v2.1+ 中使用事件系统
它似乎非常强大,但文档有些模糊。触发事件似乎非常简单,但我不确定如何注册相应的侦听器来侦听事件。相关部分在这里,它提供了以下示例代码:
App::uses('CakeEventListener', 'Event');
class UserStatistic implements CakeEventListener {
public function implementedEvents() {
return array(
'Model.Order.afterPlace' => 'updateBuyStatistic',
);
}
public function updateBuyStatistic($event) {
// Code to update statistics
}
}
// Attach the UserStatistic object to the Order's event manager
$statistics = new UserStatistic();
$this->Order->getEventManager()->attach($statistics);
但它没有说明此代码应位于何处。在特定的控制器内部?在应用程序控制器内部?
如果相关,监听器将是我正在编写的插件的一部分。
更新:听起来一种流行的方法是将侦听器注册码放在插件的引导.php文件中。但是,我无法弄清楚如何从那里调用getEventManager(),因为应用程序的控制器类等不可用。
更新 2:我还被告知,听众可以住在模特里面。
更新 3:终于有一些牵引力了!以下代码将在我的 MyPlugin/Config/bootstrap 中成功记录事件.php
App::uses('CakeEventManager', 'Event');
App::uses('CakeEventListener', 'Event');
class LegacyWsatListener implements CakeEventListener {
public function implementedEvents() {
return array(
'Controller.Attempt.complete' => 'handleLegacyWsat',
);
}
public static function handleLegacyWsat($event) { //method must be static if used by global EventManager
// Code to update statistics
error_log('event from bootstrap');
}
}
CakeEventManager::instance()->attach(array('LegacyWsatListener', 'handleLegacyWsat'), 'Controller.Attempt.complete');
我不知道为什么,但是当我尝试将两者组合成一行时,我不会得到错误。App::uses()