CakePHP 3 Controller Event Implementation Example

為{幸葍}努か 提交于 2021-02-18 18:16:35

问题


The CakePHP 3.0 documentation includes an example of how to create an event using a model as an example. I've tried and tried and it's just not translating for me. Does anyone have a CakePHP 3.x example of using a custom event where a controller sets a variable in the controller triggering the event?


回答1:


Let's say we have an admin dashboard that you want to inject some code into using events so that you can decouple your plugins and not hard code dashboard functionality for particular plugins into the core admin dashboard.

Create the firing of the event.

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...
}

Now create a listener that waits for that event to be triggered

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');
    }
}

Finally turn the listener on. (ex. at the bottom of 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);


来源:https://stackoverflow.com/questions/36392739/cakephp-3-controller-event-implementation-example

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!