Skip to content

Instantly share code, notes, and snippets.

@weierophinney
Last active June 17, 2016 09:11
Show Gist options
  • Save weierophinney/9670494 to your computer and use it in GitHub Desktop.
Save weierophinney/9670494 to your computer and use it in GitHub Desktop.
404 listener in ZF2
<?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'));
}
}
<?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);
}
}
@weierophinney
Copy link
Author

@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