我已经设置了路由器,并在其中为404s定义了路由:
<?php
use Phalcon\Mvc\Router;
$router = new Router(FALSE);
$router->removeExtraSlashes(true);
$route = $router->add('/', ['controller' => 'index', 'action' => 'index']);
$route->setName("index");
// other routes defined here...
$router->notFound([
"controller" => "index",
"action" => "route404"
]);
?>
我的IndexController:
<?php
class IndexController extends ControllerBase
{
public function indexAction()
{
// code removd for berevity
}
public function route404Action() {
// no code here, I just need to show the view.
}
}
?>
我有一个@ /app/views/index/route404.phtml
的视图,其中只有一些HTML,我甚至尝试将其设为.volt
文件,没有运气。
当我转到与任何路线不匹配的页面时,它工作正常。但是,如果我尝试重定向到它,我只会得到一个空白页面。例如,在我的一个控制器中,我有这个:
if (!$category) {
// show 404
//Tried this next line to test, and it indeed does what you'd expect, I see "Not Found".
// echo "Not Found"; exit;
$response = new \Phalcon\Http\Response();
$response->redirect([
"for" => "index",
"controller" => "index",
"action" => "route404"]
);
return; // i return here so it won't run the code after this if statement.
}
有什么想法吗?该页面完全空白(源代码中没有任何内容),并且我的apache日志中没有错误。
答案 0 :(得分:3)
尝试返回响应对象,而不仅仅是返回空白。例如:
return $this->response->redirect(...);
但是我建议您使用从调度员转发来显示404页面。这样,用户将保持在相同的URL上,并且浏览器将接收正确的状态代码(404)。它也是这种方式的SEO友好:)
示例:
if ($somethingFailed) {
return $this->dispatcher->forward(['controller' => 'index', 'action' => 'error404']);
}
// Controller method
function error404Action()
{
$this->response->setStatusCode(404, "Not Found");
$this->view->pick(['_layouts/error-404']);
$this->response->send();
}