繁体   English   中英

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

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

默认情况下, 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'这样'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'模板?

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

这是它在Module.php中的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' );
    });
}

我用它来管理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作为参数调用路径(在我的示例索引中)

我希望能帮助你。

我不确定我是否遵循了你想要实现的目标,你能给出一个明确的例子吗?

如果您只是尝试将变量添加到传递的视图模型中,您甚至可以在控制器中执行此操作,请查看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',
    ));
}

第一件事是创建视图:

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

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

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

在应用程序的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',
        ),
   // [...]
    ),

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

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

/* @var \Zend\Mvc\View\Http\RouteNotFoundStrategy $strategy */
$strategy = $this->getServiceLocator()->get('HttpRouteNotFoundStrategy');
$strategy->setNotFoundTemplate('application/other/404');

$view = new ViewModel();
//$view->setTemplate('application/other/404');
return $view;

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM