如何在Phalcon中设置404页面

2022-08-30 19:29:54

如何在Phalcon中设置404页面,以便在控制器/操作不存在时显示?


答案 1

您可以设置调度程序为您执行此操作。

当您引导应用程序时,您可以执行此操作(是您的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>

答案 2

您可以使用路由来处理 404 未找到的页面:

$router->notFound(array(
    "controller" => "index",
    "action" => "route404"
));

编号: http://docs.phalconphp.com/en/latest/reference/routing.html#not-found-paths


推荐