phphttp-status-code-404phalconvolt

How to setup a 404 page in Phalcon


How can I set a 404 page in Phalcon to be displayed when a controller/action does not exist?


Solution

  • You can set the dispatcher to do that for you.

    When you bootstrap your application you can do this ($di is your DI factory):

    use \Phalcon\Mvc\Dispatcher as PhDispatcher;
    
    $di->set(
        'dispatcher',
        function() use ($di) {
    
            $evManager = $di->getShared('eventsManager');
    
            $evManager->attach(
                "dispatch:beforeException",
                function($event, $dispatcher, $exception)
                {
                    switch ($exception->getCode()) {
                        case PhDispatcher::EXCEPTION_HANDLER_NOT_FOUND:
                        case PhDispatcher::EXCEPTION_ACTION_NOT_FOUND:
                            $dispatcher->forward(
                                array(
                                    'controller' => 'error',
                                    'action'     => 'show404',
                                )
                            );
                            return false;
                    }
                }
            );
            $dispatcher = new PhDispatcher();
            $dispatcher->setEventsManager($evManager);
            return $dispatcher;
        },
        true
    );
    

    Create an ErrorController

    <?php
    
    /**
     * ErrorController 
     */
    class ErrorController extends \Phalcon\Mvc\Controller
    {
        public function show404Action()
        {
            $this->response->setStatusCode(404, 'Not Found');
            $this->view->pick('404/404');
        }
    }
    

    and a 404 view (/views/404/404.volt)

    <div align="center" id="fourohfour">
        <div class="sub-content">
            <strong>ERROR 404</strong>
            <br />
            <br />
            You have tried to access a page which does not exist or has been moved.
            <br />
            <br />
            Please click the links at the top navigation bar to 
            navigate to other parts of the site, or
            if you wish to contact us, there is information in the About page.
            <br />
            <br />
            [ERROR]
        </div>
    </div>