Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fallback to IndexController when Controller not exist in Phalcon?

When I enter url like:

http://localhost/asdfasdfasdcxccarf

Phalcon is giving me this message:

PhalconException: AsdfasdfasdcxccarfController handler class cannot be loaded

Which is logical, because this controller doesn't exist.

However, how can I make Phalcon to redirect every bad url that doesn't have controller to my default controller IndexController?

like image 233
user3797244 Avatar asked Dec 14 '22 21:12

user3797244


1 Answers

You can add following dispatcher service to the dependency injection container. It will check for internal Phalcon errors (like wrong controller for example) and forward user to the specified controller and action:

$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);
like image 62
Phantom Avatar answered Dec 17 '22 10:12

Phantom