Nik*_*los 19 php http-status-code-404 phalcon volt
如果控制器/操作不存在,如何在Phalcon中设置404页面?
Nik*_*los 43
您可以设置调度程序为您执行此操作.
当您引导应用程序时,您可以执行此操作($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
);
Run Code Online (Sandbox Code Playgroud)
创建一个 ErrorController
<?php
/**
* ErrorController
*/
class ErrorController extends \Phalcon\Mvc\Controller
{
public function show404Action()
{
$this->response->setStatusCode(404, 'Not Found');
$this->view->pick('404/404');
}
}
Run Code Online (Sandbox Code Playgroud)
和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>
Run Code Online (Sandbox Code Playgroud)
Ngu*_*ằng 12
您可以使用路由来处理404未找到的页面:
$router->notFound(array(
"controller" => "index",
"action" => "route404"
));
Run Code Online (Sandbox Code Playgroud)
参考:http://docs.phalconphp.com/en/latest/reference/routing.html#not-found-paths
Dimopoulos提出的解决方案不起作用.它会产生一种循环条件.
Phalcon路由器组件具有默认行为,提供非常简单的路由,始终需要与以下模式匹配的URI:/:controller /:action /:params.这将导致许多问题,因为当服务器收到与任何已定义路由不匹配的URL的请求时,Phalcon将搜索不存在的控制器.
因此,首先,您必须禁用此行为.这可以FALSE在创建路由器实例期间完成,如下所示:
$router = Phalcon\Mvc\Router(FALSE);
Run Code Online (Sandbox Code Playgroud)
此时,您可以使用@NguyễnTrọngBằng提出的解决方案.
$router->notFound(
[
"namespace" => "MyNamespace\Controller"
"controller" => "index",
"action" => "route404"
]
);
Run Code Online (Sandbox Code Playgroud)
重要的是要注意,如果您使用命名空间,调度程序将无法找到控制器,除非您指定它,就像我上面所做的那样.
这不仅是最简单的解决方案,而且是唯一有效的解决方案.