ZF2 - How to change the error/404 response page? Not just template but to set a new ViewModel

前端 未结 7 2537
离开以前
离开以前 2021-01-05 22:46

By default the page is set like this in the Application module.config array:

\'template_map\' => array(
    \'error/404\' => __DIR__ . \'/         


        
7条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-05 23:31

    I used this to manage 404 error (I moved my website from spip to ZF2 based cms) :

    In module onBootstrap function :

    $eventManager->getSharedManager()->attach('*', MvcEvent::EVENT_DISPATCH_ERROR, array($this, 'onDispatchError'), -100);
    

    Then

    public function onDispatchError(MvcEvent $event)
    {
        $response = $event->getResponse();
        if ($response->getStatusCode() == 404) {
            $url = $event->getRouter()->assemble(array(), array('name' => 'index'));
            $requestUri = $event->getRequest()->getRequestUri();
            $response->getHeaders()->addHeaderLine('Location', "$url?url=$requestUri");
            $response->setStatusCode(200);
            $response->sendHeaders();
            $event->stopPropagation(true);
        } elseif($response->getStatusCode() == 500){
            //DO SOMETHING else?
            return;
         }
    }
    

    In this code we never return a 404 error, we just call the route (in my example index) with the requested url as param

    I hope that help you.

提交回复
热议问题