Reputation: 2643
I'm trying to add something like this into a non-micro app, but I'm unsure of how to go about doing that without rolling my own EventsManager. Is there a way to get a reference to Phalcon's default EventsManager?
$eventsManager->attach("dispatch", function($event, $dispatcher, $exception) {
if ($event->getType() == 'beforeException') {
switch ($exception->getCode()) {
case Phalcon\Dispatcher::EXCEPTION_HANDLER_NOT_FOUND:
case Phalcon\Dispatcher::EXCEPTION_ACTION_NOT_FOUND:
$dispatcher->forward(array(
'controller' => 'errors',
'action' => 'show404'
));
return false;
}
}
});
Thoughts?
Thanks!
Upvotes: 2
Views: 1438
Reputation: 9085
Of course there is. Your dispatcher must be injected into your DI as a service with the same name. If your $eventsManager
is an instance of Phalcon\DI\Injectable
:
$this->dispatcher->forward(…);
$this->di->get('dispatcher')->forward(…);
If not:
DI::getDefault()->get('dispatcher')->forward(…);
Edit:
Yep, that isn't very clear from the docs that there is a shared Events Manager, all examples I saw show only the usage of a freshly created instance. Looking at the code of the Di/FactoryDefault it seems there is a service for that with the same name. You can get it using the same syntax as above.
DI::getDefault()->get('eventsManager')->attach('dispatch', …);
The whole thing should look like this and must be setup somewhere after you configure your DI.
$di->get('eventsManager')->attach("dispatch:beforeException", function($event, $dispatcher, $exception) {
switch ($exception->getCode()) {
case Phalcon\Dispatcher::EXCEPTION_HANDLER_NOT_FOUND:
case Phalcon\Dispatcher::EXCEPTION_ACTION_NOT_FOUND:
$dispatcher->forward(array(
'controller' => 'errors',
'action' => 'show404'
));
return false;
}
});
$di->get('dispatcher')->setEventsManager($di->get('eventsManager'));
Upvotes: 2