We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Controller getEventsManager()

How would I use DI to set the EventsManager exposed by Phalcon\Mvc\Controller ?

I want to attach a custom event listener to all controllers. eg. I have a class NotificationCentre that performs as an event listener, and would like to call something like $this->getEventsManager()->fire('notification:myAction', $data);



98.9k
Accepted
answer

Set the eventsManager in the DI:

$di['eventsManager'] = function() {
    $ev =  new Phalcon\Events\Manager();
    $ev->attach('notification', new NotificationCenter());
    return $ev;
};

Then in your controller you can trigger events in to the listeners:

public function indexAction()
{
    $this->eventsManager->fire('notification:myAction', $this, $data);
}