Last active
June 17, 2016 09:11
-
-
Save weierophinney/9670494 to your computer and use it in GitHub Desktop.
404 listener in ZF2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Module | |
{ | |
public function onBootstrap($e) | |
{ | |
$app = $e->getApplication(); | |
$events = $app->getEventManager(); | |
// Direct instantiation | |
$events->attach(new RouteNotFoundListener()); | |
// Or pull from service container, assuming you've registered it | |
$services = $app->getServiceManager(); | |
$events->attach($services->get('RouteNotFoundListener')); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Zend\EventManager\AbstractListenerAggregate; | |
use Zend\EventManager\EventManagerInterface; | |
use Zend\Mvc\Application; | |
use Zend\Mvc\Router\RouteMatch; | |
class RouteNotFoundListener extends AbstractListenerAggregate | |
{ | |
public function attach(EventManagerInterface $events) | |
{ | |
$events->attach('dispatch.error', array($this, 'onDispatchError'), 1000); | |
} | |
public function onDispatchError($e) | |
{ | |
if ($e->getError() !== Application::ERROR_ROUTER_NO_MATCH) { | |
// Not a 404 error | |
return; | |
} | |
$e->setError(false); | |
$e->setRouteMatch(new RouteMatch(array( | |
'controller' => 'SomeCustomErrorController', | |
'action' => 'actionMethodIfAny', | |
/* ... other params? ...*/ | |
))); | |
$e->stopPropagation(true); | |
} | |
} |
@ppeiris Actually, that's not a great solution, as it does not mimic the event loop within the application perfectly (it doesn't trigger the finish
event, and thus the view may not get rendered, etc.).
I've updated the gist to do the following:
- Push the route match into the event
- Clear the error in the event
- Stop propagation of the event (because at this point, we know we need to handle a 404; there's no further handlers we should fire)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The last two lines are added to make this work