ZF2 - 如何更改错误/ 404响应页面?不只是模板,而是设置新的ViewModel

时间:2012-12-10 19:31:50

标签: php zend-framework2 http-status-code-404 zend-view zend-framework-mvc

默认情况下,页面在Application module.config数组中设置如下:

'template_map' => array(
    'error/404' => __DIR__ . '/../view/error/404.phtml'

我想要更改页面。我希望新的ViewModel充满变量。这意味着仅仅改变模板是不够的:

'error/404' => __DIR__ . '/../view/error/my_new_404_template.phtml'

但我无法理解如何制作它。我无法看到请求到'error/404'的方式。

  • 如何为它创建新的ViewModel

  • 如何将变量附加到它?

  • 路由如何通过'error/404'来改变它?

例如,我有'error/404'页面的这种方法:

public function pageNotFoundAction() {

    $view = new ViewModel();

    $view->setTemplate('error/404');     // set my template

    $sm = $this->getServiceLocator()->get('SessionManager');
    $cont = new Container('SomeNamespace', $sm);

    $view->var1 = $cont->offsetGet('someValue1');   // the "error/404" template
    $view->var2 = $cont->offsetGet('someValue2');   //       is full of variables
    $view->var3 = $cont->offsetGet('someValue3');
    $view->var4 = "One more view variable";

    // And now I return it somewhere and want it to be called
    //    in case of "the page is not found"
    return $view;
}

如何做出这样的改变?我无法获得他们创建的系统来处理'error/404'之类的事情。请帮忙。

UPD 1

更复杂的任务。如何拥有多个'error/404'页面? 想问一下创建框架的人是否知道'not_found_template'不能拥有'error/404'个页面的数组。它怎么样?如果我像这样设置这个选项:

'template_map' => array(
    'error/404' => __DIR__ . '/../view/error/404.phtml',
    'my-page/one_more_error404' => __DIR__ . '/../view/my-page/my-page/one_more_error404.phtml',
    'other_page/second_404' => __DIR__ . '/../view/other-page/one_more_error404.phtml',

'not_found_template' => array(
    'error/404',
    'my-page/one_more_error404',
    'other-page/second_404',
);

它会抛出错误。 'not_found_template'强迫您只拥有一个'error/404'模板?

7 个答案:

答案 0 :(得分:5)

还有另一种方式。捕获EVENT_DISPATCH_ERROR并完全重建viewModel。 Cavern是布局 - 是根viewModel,默认情况下附加到布局中的内容是另一个viewModel(子)。官方文档中没有明确说明这些要点。

以下是Module.php

中的效果
public function onBootstrap(MvcEvent $event)
{
    $app = $event->getParam( 'application' );
    $eventManager = $app->getEventManager();


    /** attach Front layout for 404 errors */
    $eventManager->attach( MvcEvent::EVENT_DISPATCH_ERROR, function( MvcEvent $event ){

        /** here you can retrieve anything from your serviceManager */
        $serviceManager = $event->getApplication()->getServiceManager();
        $someVar = $serviceManager->get( 'Some\Factory' )->getSomeValue();

        /** here you redefine layout used to publish an error */
        $layout = $serviceManager->get( 'viewManager' )->getViewModel();
        $layout->setTemplate( 'layout/start' );

        /** here you redefine template used to the error exactly and pass custom variable into ViewModel */
        $viewModel = $event->getViewModel();
        $viewModel->setVariables( array( 'someVar' => $someVar ) )
                  ->setTemplate( 'error/404' );
    });
}

答案 1 :(得分:3)

我用它来管理404错误(我将我的网站从spip移到了基于ZF2的cms):

在模块onBootstrap函数中:

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

然后

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;
     }
}

在这段代码中,我们永远不会返回404错误,我们只是将请求的URL作为参数调用路径(在我的示例索引中)

我希望能帮到你。

答案 2 :(得分:2)

我不确定我是否遵循了您想要实现的目标,您能否举例说明您的目标?

如果您只是尝试将变量添加到传递的视图模型中,您甚至可以在控制器中执行此操作,请查看 AbstractActionController

/**
 * Action called if matched action does not exist
 *
 * @return array
 */
public function notFoundAction()
{
    $response   = $this->response;
    $event      = $this->getEvent();
    $routeMatch = $event->getRouteMatch();
    $routeMatch->setParam('action', 'not-found');

    if ($response instanceof HttpResponse) {
        return $this->createHttpNotFoundModel($response);
    }
    return $this->createConsoleNotFoundModel($response);
}

/**
 * Create an HTTP view model representing a "not found" page
 *
 * @param  HttpResponse $response
 * @return ViewModel
 */
protected function createHttpNotFoundModel(HttpResponse $response)
{
    $response->setStatusCode(404);

    // Add in extra stuff from your ServiceLocator here...

    // $viewModel->setTemplate(..); 

    return new ViewModel(array(
        'content' => 'Page not found',
    ));
}

答案 3 :(得分:2)

首先是创建视图:

  

模块/ Yourapplication /视图/ yourapplication /错误/ index.phtml

     

模块/ Yourapplication /视图/ yourapplication /错误/ 404.phtml

第二件事是在模块config中注册视图:

在你的应用程序的module.config.php中

'view_manager' => array(
        //[...]
        'not_found_template'       => 'error/404',
        'exception_template'       => 'error/index',
        'template_map' => array(
        //[...]
        'error/404'   => __DIR__ . '/../view/yourapplication/error/404.phtml',
        'error/index' => __DIR__ . '/../view/yourapplication/error/index.phtml',
        ),
   // [...]
    ),

答案 4 :(得分:2)

module.php中,您还可以更改模板和布局。

function onBootstrap(EventInterface $e) {
  $app = $e->getApplication();
  $evt = $app->getEventManager();
  $evt->attach(MvcEvent::EVENT_DISPATCH_ERROR, array($this,'onDispatchError'), 100);    
}

function onDispatchError(MvcEvent $e) {
  $vm = $e->getViewModel();
  $vm->setTemplate('layout/blank');
}

答案 5 :(得分:1)

或者更简单(你想要的地方):

lib

答案 6 :(得分:0)

您应首先分离默认的notfoundstrategy并在Module.php中,如果是404,您应该从控制器返回一个新的viewmodel。请参阅此帖子:http://www.cagataygurturk.com/zf2-controller-specific-not-found-page/