Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to setup a 404 page in Phalcon

Tags:

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

like image 725
Nikolaos Dimopoulos Avatar asked Dec 28 '12 14:12

Nikolaos Dimopoulos


2 Answers

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> 
like image 58
Nikolaos Dimopoulos Avatar answered Oct 02 '22 19:10

Nikolaos Dimopoulos


You can use routing to handle 404 not found page:

$router->notFound(array(     "controller" => "index",     "action" => "route404" )); 

Ref: http://docs.phalconphp.com/en/latest/reference/routing.html#not-found-paths

like image 24
Nguyễn Trọng Bằng Avatar answered Oct 02 '22 19:10

Nguyễn Trọng Bằng