当Phalcon中不存在Controller时,如何回退到IndexController?

时间:2014-07-02 10:39:50

标签: php phalcon phalcon-routing

当我输入url时:

http://localhost/asdfasdfasdcxccarf

Phalcon正在给我这样的信息:

PhalconException: AsdfasdfasdcxccarfController handler class cannot be loaded

这是合乎逻辑的,因为这个控制器不存在。

但是,如何让Phalcon将每个没有控制器的坏网址重定向到我的默认控制器IndexController?

2 个答案:

答案 0 :(得分:8)

您可以将以下调度程序服务添加到依赖项注入容器。它将检查内部Phalcon错误(例如错误的控制器)并将用户转发到指定的控制器和操作:

$di->set('dispatcher', function() {

    $eventsManager = new \Phalcon\Events\Manager();

    $eventsManager->attach("dispatch:beforeException", function($event, $dispatcher, $exception) {

        //Handle 404 exceptions
        if ($exception instanceof \Phalcon\Mvc\Dispatcher\Exception) {
            $dispatcher->forward(array(
                'controller' => 'index',
                'action' => 'show404'
            ));
            return false;
        }

        //Handle other exceptions
        $dispatcher->forward(array(
            'controller' => 'index',
            'action' => 'show503'
        ));

        return false;
    });

    $dispatcher = new \Phalcon\Mvc\Dispatcher();

    //Bind the EventsManager to the dispatcher
    $dispatcher->setEventsManager($eventsManager);

    return $dispatcher;

}, true);

答案 1 :(得分:2)

您可以在初始化中设置默认路由:

$di->set('router', function() {
    $router = new \Phalcon\Mvc\Router();

    //your routes here

    $router->setDefaults(array(
        'controller' => 'index',
        'action' => 'index'
    ));

    return $router;
});

所以, 当调度员未找到行动时,他将使用CurentController => indexAction 否则,当调度员找不到控制器时,他将使用IndexController => indexAction