We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Routing non-controller urls to page controller for database-stored pages?

I'm currently building a CMS using phalcon, and so far I haven't had any issues until now. Currently, I'd like any urls that do not have an associated controller to load the "page" controller I have, which will attempt to find a database-stored page and produce the 404 if one is not found. I've looked at the router documentation about setting a default controller, but that doesn't seem to work, as it always throws the exception error that the controller couldn't be loaded.

I assume what I would need to do is create an event handler for the exception messages, but the documentation has got my eyes crossing, since I'm not understanding how to implement a listener to handle the exception messages.

Any ideas what I should be doing to accomplish this?



804
Accepted
answer
edited Apr '14

I figured this out a few minutes ago. For those who are experiencing the same issue, you need to attach an event listener on the 'dispatcher:beforeException' hook to forward the system via dispatcher to a specific controller. This should be done in the main bootstrap file when setting up the dispatcher.

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

        $eventsManager = $di->getShared('eventsManager');

        // If the path does not match a pre-defined controller, send it to a specific controller for handling
        $eventsManager->attach('dispatch:beforeException', 
            function($event, $dispatcher, $exception){
                switch ($exception->getCode()) {
                    case Phalcon\Mvc\Dispatcher::EXCEPTION_HANDLER_NOT_FOUND:
                    case Phalcon\Mvc\Dispatcher::EXCEPTION_ACTION_NOT_FOUND:
                        $dispatcher->forward(
                            array(
                                'controller' => '[CONTROLLER_NAME_HERE]',
                                'action'     => '[ACTION_NAME_HERE]',
                            )
                        );
                        return false;
                }                
            }
        );

        $dispatcher = new Phalcon\Mvc\Dispatcher();
        $dispatcher->setEventsManager($eventsManager);

        return $dispatcher;
    });