当控制器/操作不存在时,如何在Phalcon中设置要显示的404页面?
发布于 2012-12-28 22:47:33
您可以设置dispatcher为您执行此操作。
当你引导你的应用程序时,你可以这样做($di
是你的DI工厂):
use \Phalcon\Mvc\Dispatcher as PhDispatcher;
$di->set(
'dispatcher',
function() use ($di) {
$evManager = $di->getShared('eventsManager');
$evManager->attach(
"dispatch:beforeException",
function($event, $dispatcher, $exception)
{
switch ($exception->getCode()) {
case PhDispatcher::EXCEPTION_HANDLER_NOT_FOUND:
case PhDispatcher::EXCEPTION_ACTION_NOT_FOUND:
$dispatcher->forward(
array(
'controller' => 'error',
'action' => 'show404',
)
);
return false;
}
}
);
$dispatcher = new PhDispatcher();
$dispatcher->setEventsManager($evManager);
return $dispatcher;
},
true
);
创建ErrorController
<?php
/**
* ErrorController
*/
class ErrorController extends \Phalcon\Mvc\Controller
{
public function show404Action()
{
$this->response->setStatusCode(404, 'Not Found');
$this->view->pick('404/404');
}
}
和404视图(/views/404/404.volt
)
<div align="center" id="fourohfour">
<div class="sub-content">
<strong>ERROR 404</strong>
<br />
<br />
You have tried to access a page which does not exist or has been moved.
<br />
<br />
Please click the links at the top navigation bar to
navigate to other parts of the site, or
if you wish to contact us, there is information in the About page.
<br />
<br />
[ERROR]
</div>
</div>
发布于 2014-07-09 16:09:51
您可以使用路由来处理404找不到页面:
$router->notFound(array(
"controller" => "index",
"action" => "route404"
));
参考:http://docs.phalconphp.com/en/latest/reference/routing.html#not-found-paths
发布于 2013-09-13 04:02:12
还可以使用以下命令在errorController中设置标头
class ErrorController extends ControllerBase
{
public function error404Action()
{
$this->response->setHeader('HTTP/1.0 404','Not Found');
// $this->response->setHeader(404, 'Not Found'); <- did not work
}
}
在此之前,在控制器中,当发生错误时,您可以转发到这个错误控制器。
class IndexController extends ControllerBase
{
public function indexAction()
{
$id = (int)$this->getId($param);
if ($id > 0) {
// do you stuff
} else {
$this->dispatcher->forward(array(
'controller' => 'error', 'action' => 'error404')
);
}
}
}
这是一个又快又脏的(?)如果你想从数据库中获取内容,并且想抛出一个错误,如果什么都没有找到,那么这个方法是很好的。
https://stackoverflow.com/questions/14071261
复制相似问题