当找不到模型时,我希望我的控制器返回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',
));
}
谢谢。
看起来您混淆了传递到视图的推理短语和推理变量。reasonphrase是http状态代码的一部分,类似于404的"未找到"。你可能不想改变这一点。
就像@dphn所说的,我建议抛出您自己的Exception,并在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
);
}
error/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',
),