4

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?

Phantom
  • 1,704
  • 4
  • 17
  • 32
user3797244
  • 53
  • 1
  • 5

2 Answers2

10

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);
Phantom
  • 1,704
  • 4
  • 17
  • 32
2

You can set default route in you di initialization:

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

    //your routes here

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

    return $router;
});

So, when dispathcer not found action he will use CurentController => indexAction else, when dispatcher not found controller he will use IndexController => indexAction

Barif
  • 1,552
  • 3
  • 17
  • 28