ZF2 Event before not_found_template

2019-07-20 13:34发布

问题:

Is there an event in zf2 i can attach to the sharedEventManager/eventManager which is called before the not_found_template is set? I want to implement a "under construction page" Module on my website. Everything works fine if a existing route is called. But when a non existing route is called the standard 404 error page is shown, because the route wasnt found.

Thats my Module.php

public function onBootstrap(Event $e)
{
    $e->getApplication()->getEventManager()->getSharedManager()->attach(
        'Zend\Mvc\Controller\AbstractActionController', 'dispatch', function ($e) {
            $e->getTarget()->layout('layout/underconstruction');
        }, -1000
    );

}

Anybody of you got an idea?

Thank you very much

回答1:

It's pointless listening to the dispatch event, since the route can't find a controller to dispatch to, instead listen to the render event and setTemplate on the view model, something like this should work

$e->getApplication()->getEventManager()->attach(MvcEvent::EVENT_RENDER, function ($e) {        
    $response = $e->getResponse();
    if ($response->getStatusCode() == 404) {
        $e->getViewModel()->setTemplate('layout/underconstruction');
    }
}, -1000);