CakePHP 3 控制器事件实现示例
CakePHP 3 Controller Event Implementation Example
CakePHP 3.0 文档包含一个示例,说明如何使用模型创建事件。我试了又试,但它并没有为我翻译。有没有人有使用自定义事件的 CakePHP 3.x 示例,其中控制器在触发事件的控制器中设置变量?
假设我们有一个管理仪表板,您想将一些代码注入到使用事件中,以便您可以分离插件,而不是将特定插件的仪表板功能硬编码到核心管理仪表板中。
创建事件的触发。
In APP/Controller/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...
}
现在创建一个等待该事件被触发的侦听器
A good place for this might be 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, this listener initialization can be anywhere that fires before DashboardController::index
// Attach event listeners
use Cake\Event\EventManager;
use PluginName\Controller\Event\DashboardListener;
$myPluginListener = new DashboardListener();
EventManager::instance()->on($myPluginListener);
CakePHP 3.0 文档包含一个示例,说明如何使用模型创建事件。我试了又试,但它并没有为我翻译。有没有人有使用自定义事件的 CakePHP 3.x 示例,其中控制器在触发事件的控制器中设置变量?
假设我们有一个管理仪表板,您想将一些代码注入到使用事件中,以便您可以分离插件,而不是将特定插件的仪表板功能硬编码到核心管理仪表板中。
创建事件的触发。
In APP/Controller/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...
}
现在创建一个等待该事件被触发的侦听器
A good place for this might be 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, this listener initialization can be anywhere that fires before DashboardController::index
// Attach event listeners
use Cake\Event\EventManager;
use PluginName\Controller\Event\DashboardListener;
$myPluginListener = new DashboardListener();
EventManager::instance()->on($myPluginListener);