【问题标题】:Zend Framework 2 : set reason phrase for error 404Zend Framework 2:设置错误 404 的原因短语
【发布时间】:2013-12-30 00:00:04
【问题描述】:

我希望我的控制器在找不到模型时返回 404 响应,并且我想指定自定义消息,而不是默认的“The requested controller was unable to dispatch the request.

我尝试在ViewModel 中指定reason,从响应对象中设置reasonPhrase...似乎没有任何效果。我目前正在研究如何防止默认行为,但如果有人在我之前知道,那就太好了。 (也许还有一种比我无论如何都能找到的更好的方法。)

这是我所拥有的,但不起作用:

 $userModel = $this->getUserModel();
 if (empty($userModel)) {
     $this->response->setStatusCode(404);
     $this->response->setReasonPhrase('error-user-not-found');
     return new ViewModel(array(
         'content' => 'User not found',
     ));
 }

谢谢。

【问题讨论】:

  • "请求的控制器无法发送请求。"由页面未找到事件处理程序返回,而不是您的控制器。
  • 查看 404 模板。如果使用 Application 模块,请参阅 Application/view/error/404.phtml switch ($this->reason) { ... }
  • @dphn,是的,关键是我在控制器中设置了原因,它在渲染阶段之间被覆盖。
  • @imel96,你能详细说明一下吗?评论本身无助于解决这里的问题。
  • 控制器由 EventManager 在 EVENT_DISPATCH 事件中调度,但前提是它可以被调度。如果不能,则将触发 EVENT_DISPATCH_ERROR,您的代码将不会被执行,它将显示 view/error/404.phtml。 Otoh,如果调度了控制器,您的代码对我来说看起来不错。抱歉,如果不回答,我猜是路由问题?

标签: php http-headers zend-framework2 http-status-code-404


【解决方案1】:

看起来您混淆了 reasponphrase 和传递给视图的原因变量。原因短语是 http 状态代码的一部分,例如 404 的“未找到”。您可能不想更改它。

就像@dphn 所说,我建议您抛出自己的异常并将一个侦听器附加到决定响应内容的MvcEvent::EVENT_DISPATCH_ERROR

让您开始:

控制器

public function someAction()
{
    throw new \Application\Exception\MyUserNotFoundException('This user does not exist');
}

模块

public function onBootstrap(MvcEvent $e)
{
    $events = $e->getApplication()->getEventManager();

    $events->attach(
        MvcEvent::EVENT_DISPATCH_ERROR,
        function(MvcEvent $e) {
            $exception = $e->getParam('exception');
            if (! $exception instanceof \Application\Exception\MyUserNotFoundException) {
                return;
            }

            $model = new ViewModel(array(
                'message' => $exception->getMessage(),
                'reason' => 'error-user-not-found',
                'exception' => $exception,
            ));
            $model->setTemplate('error/application_error');
            $e->getViewModel()->addChild($model);

            $response = $e->getResponse();
            $response->setStatusCode(404);

            $e->stopPropagation();

            return $model;
        },
        100
    );
}

错误/application_error.phtml

<h1><?php echo 'A ' . $this->exception->getStatusCode() . ' error occurred ?></h1>
<h2><?php echo $this->message ?></h2>  
<?php
switch ($this->reason) {
    case 'error-user-not-found':
      $reasonMessage = 'User not found';
      break;
}
echo $reasonMessage;

module.config.php

'view_manager' => array(
    'error/application_error' => __DIR__ . '/../view/error/application_error.phtml',
),

【讨论】:

    猜你喜欢
    • 2012-08-26
    • 2013-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多