Thursday, January 29, 2009

Manage ‘Invalid controller specified’ Error with Default controller

It’s quite obvious that the site users will go wherever they want with our domain name. If you work with Zend frame work and calls a non existing Controller then it causes showing an ugly error message on the screen telling the Controller not found.

We have the function __cal() to catch all the non existing function within a controller, but we couldn’t go for a default controller. We have to use Plugins to manage this section. In Zend Framework, plugins are used to listen for certain events in the front controller.

preDispatch() Event
This event will fire prior to dispatching an individual action. So before that we can check the existence.

Action helper code

The class location
library/Zend/Controller/Action/Helper/ ControllerSetup.php


class Zend_Controller_Action_Helper_ControllerSetup extends Zend_Controller_Plugin_Abstract
{
public function preDispatch(Zend_Controller_Request_Abstract $request)
{
require_once("Zend/Controller/Front.php");
$dispatcher = Zend_Controller_Front::getInstance()->getDispatcher();
if (!$dispatcher->isDispatchable($request))
{
$request->setControllerName('Index')
->setActionName('index')
->setDispatched(false);
}
}
}


Include the class into bootstrap file

Zend_Loader::loadClass('Zend_Controller_Action_Helper_ControllerSetup');


Initialize the Controller Front Object

$frontController = Zend_Controller_Front::getInstance();


Register the Plug In

$frontController->registerPlugin(new Zend_Controller_Action_Helper_ControllerSetup());


That’s it

Here I redirected to the Index Controller and Index Action, You can make your own 404 error page and set to that page easily.


If you use an alternative to this solution, share it with us in the Comments section!

1 comments:

  1. Perfect, thanks. I don't know what the speed hit to this class but it works great.

    ReplyDelete