Setting Custom 404 Controller in Phalcon

After CodeIgniter, Phalcon was the second PHP framework that I used. Blazingly fast and easy-to-use, one of the first things I did was create a custom 404 response controller.

This works for Phalcon 2.0.13.

You can set up a custom 404 controller and method in Phalcon using the Dispatcher. Just replace the CONTROLLER_NAME and METHOD_NAME in the code below with your choice of controller and method.

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

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

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

        // Handle 404
        if ( $exception instanceof \Phalcon\Mvc\Dispatcher\Exception ) {
            $dispatcher->forward ( array (
                                       'controller' => 'CONTROLLER_NAME',
                                       'action'     => 'METHOD_NAME'
                                   ) );

            return FALSE;
        }

        // Handle others
        $dispatcher->forward ( array (
                                   'controller' => 'CONTROLLER_NAME',
                                   'action'     => 'METHOD_NAME'
                               ) );

        return FALSE;
    } );

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

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

    return $dispatcher;

}, TRUE );

← previous post
DNS Record Types

next post →
Reading JWT token in Phalcon

17TechnologyView source