CakePHP 3.0 文档包含如何使用模型创建事件的示例。我试了又试,但它不适合我。有谁有使用自定义事件的 CakePHP 3.x 示例,其中控制器在触发事件的控制器中设置变量?
假设我们有一个管理仪表板,您希望使用事件将一些代码注入其中,以便您可以将插件解耦,而不是将特定插件的仪表板功能硬编码到核心管理仪表板中。
创建事件的触发。
在APP/控制器/DashboardController中
public function index()
{
// Once this gets to the function triggered by this event, the "$this" in the parameters will be $event->subject(). Mentioned again below.
$event = new Event('Controller.Dashboard.beforeDashboardIndex', $this)
$this->eventManager()->dispatch($event);
// your other index() code...
}
现在创建一个等待该事件被触发的侦听器
一个好地方可能是 PluginName/src/Controller/Event/DashboardListener.php
namespace Plugin\Controller\Event;
use Cake\Event\EventListenerInterface;
class DashboardListener implements EventListenerInterface {
public function implementedEvents() {
return array(
'Controller.Dashboard.beforeDashboardIndex' => 'myCustomMethod',
);
}
public function myCustomMethod($event) {
// $event->subject() = DashboardController();
$event->subject()->set('dashboardAddon', 'me me me');
}
}
最后打开监听器。 (例如,在 APP/config/bootstrap.php 的底部)
Note,此侦听器初始化可以在 DashboardController::index 之前触发的任何位置
// Attach event listeners
use Cake\Event\EventManager;
use PluginName\Controller\Event\DashboardListener;
$myPluginListener = new DashboardListener();
EventManager::instance()->on($myPluginListener);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)