# The Front Controller

## Overview

Zend_Controller_Front implements a Front Controller pattern used in Model-View-Controller (MVC) applications. Its purpose is to initialize the request environment, route the incoming request, and then dispatch any discovered actions; it aggregates any responses and returns them when the process is complete.

Zend_Controller_Front also implements the Singleton pattern, meaning only a single instance of it may be available at any given time. This allows it to also act as a registry on which the other objects in the dispatch process may draw.

Zend_Controller_Front registers a plugin broker with itself, allowing various events it triggers to be observed by plugins. In most cases, this gives the developer the opportunity to tailor the dispatch process to the site without the need to extend the front controller to add functionality.

At a bare minimum, the front controller needs one or more paths to directories containing action controllers in order to do its work. A variety of methods may also be invoked to further tailor the front controller environment and that of its helper classes.

Default Behaviour

By default, the front controller loads the ErrorHandler plugin, as well as the ViewRenderer action helper plugin. These are to simplify error handling and view renderering in your controllers, respectively.

To disable the ErrorHandler, perform the following at any point prior to calling dispatch():

    // Disable the ErrorHandler plugin:
    $front->setParam('noErrorHandler', true);

To disable the ViewRenderer, do the following prior to calling dispatch():

    // Disable the ViewRenderer helper:
    $front->setParam('noViewRenderer', true);

## Primary Methods

The front controller has several accessors for setting up its environment. However, there are three primary methods key to the front controller's functionality:

### getInstance()

getInstance() is used to retrieve a front controller instance. As the front controller implements a Singleton pattern, this is also the only means possible for instantiating a front controller object.

    $front = Zend_Controller_Front::getInstance();

### setControllerDirectory() and addControllerDirectory

setControllerDirectory() is used to tell the dispatcher where to look for action controller class files. It accepts either a single path or an associative array of module and path pairs.

As some examples:

    // Set the default controller directory:
    $front->setControllerDirectory('../application/controllers');

    // Set several module directories at once:
    $front->setControllerDirectory(array(
        'default' => '../application/controllers',
        'blog'    => '../modules/blog/controllers',
        'news'    => '../modules/news/controllers',
    ));

    // Add a 'foo' module directory:
    $front->addControllerDirectory('../modules/foo/controllers', 'foo');

If you use addControllerDirectory() without a module name, it will set the directory for the default module -- overwriting it if it already exists.

You can get the current settings for the controller directory using getControllerDirectory(); this will return an array of module and directory pairs.

### addModuleDirectory() and getModuleDirectory()

One aspect of the front controller is that you may define a modular directory structure for creating standalone components; these are called "modules".

Each module should be in its own directory and mirror the directory structure of the default module -- i.e., it should have a `/controllers/` subdirectory at the minimum, and typically a `/views/` subdirectory and other application subdirectories.

addModuleDirectory() allows you to pass the name of a directory containing one or more module directories. It then scans it and adds them as controller directories to the front controller.

Later, if you want to determine the path to a particular module or the current module, you can call getModuleDirectory(), optionally passing a module name to get that specific module directory.

### dispatch()

dispatch(Zend_Controller_Request_Abstract $request = null, Zend_Controller_Response_Abstract $response = null) does the heavy work of the front controller. It may optionally take a request object and/or a response object, allowing the developer to pass in custom objects for each.

If no request or response object are passed in, dispatch() will check for previously registered objects and use those or instantiate default versions to use in its process (in both cases, the HTTP flavor will be used as the default).

Similarly, dispatch() checks for registered router and dispatcher objects, instantiating the default versions of each if none is found.

The dispatch process has three distinct events:

- Routing

- Dispatching

- Response

Routing takes place exactly once, using the values in the request object when dispatch() is called. Dispatching takes place in a loop; a request may either indicate multiple actions to dispatch, or the controller or a plugin may reset the request object to force additional actions to dispatch. When all is done, the front controller returns a response.

### run()

Zend_Controller_Front::run($path) is a static method taking simply a path to a directory containing controllers. It fetches a front controller instance (via getInstance()), registers the path provided via setControllerDirectory(), and finally dispatches.

Basically, run() is a convenience method that can be used for site setups that do not require customization of the front controller environment.

    // Instantiate front controller, set controller directory, and dispatch in one
    // easy step:
    Zend_Controller_Front::run('../application/controllers');

## Environmental Accessor Methods

In addition to the methods listed above, there are a number of accessor methods that can be used to affect the front controller environment -- and thus the environment of the classes to which the front controller delegates.

- resetInstance() can be used to clear all current settings. Its primary purpose is for testing, but it can also be used for instances where you wish to chain together multiple front controllers.

- setDefaultControllerName() and getDefaultControllerName() let you specify a different name to use for the default controller ('index' is used otherwise) and retrieve the current value. They proxy to the dispatcher.

- setDefaultAction() and getDefaultAction() let you specify a different name to use for the default action ('index' is used otherwise) and retrieve the current value. They proxy to the dispatcher.

- setRequest() and getRequest() let you specify the request class or object to use during the dispatch process and to retrieve the current object. When setting the request object, you may pass in a request class name, in which case the method will load the class file and instantiate it.

- setRouter() getRouter() let you specify the router class or object to use during the dispatch process and to retrieve the current object. When setting the router object, you may pass in a router class name, in which case the method will load the class file and instantiate it.

  When retrieving the router object, it first checks to see if one is present, and if not, instantiates the default router (rewrite router).

- setBaseUrl() and getBaseUrl() let you specify the base URL to strip when routing requests and to retrieve the current value. The value is provided to the request object just prior to routing.

  Fully-Qualified URL is not supported

  Passing a fully-qualified URL (ie: http://example.com/) to the setBaseUrl method is not supported, and will cause issues when using the URL view helper. See ticket ZF-10923 for more details.

- setDispatcher() and getDispatcher() let you specify the dispatcher class or object to use during the dispatch process and retrieve the current object. When setting the dispatcher object, you may pass in a dispatcher class name, in which case the method will load the class file and instantiate it.

  When retrieving the dispatcher object, it first checks to see if one is present, and if not, instantiates the default dispatcher.

- setResponse() and getResponse() let you specify the response class or object to use during the dispatch process and to retrieve the current object. When setting the response object, you may pass in a response class name, in which case the method will load the class file and instantiate it.

- registerPlugin(Zend_Controller_Plugin_Abstract $plugin, $stackIndex = null) allows you to register plugin objects. By setting the optional `$stackIndex`, you can control the order in which plugins will execute.

- unregisterPlugin($plugin) let you unregister plugin objects. `$plugin` may be either a plugin object or a string denoting the class of plugin to unregister.

- throwExceptions($flag) is used to turn on/off the ability to throw exceptions during the dispatch process. By default, exceptions are caught and placed in the response object; turning on throwExceptions() will override this behaviour.

  For more information, read MVC Exceptions.

- returnResponse($flag) is used to tell the front controller whether to return the response (`TRUE`) from dispatch(), or if the response should be automatically emitted (`FALSE`). By default, the response is automatically emitted (by calling Zend_Controller_Response_Abstract::sendResponse()); turning on returnResponse() will override this behaviour.

  Reasons to return the response include a desire to check for exceptions prior to emitting the response, needing to log various aspects of the response (such as headers), etc.

## Front Controller Parameters

In the introduction, we indicated that the front controller also acts as a registry for the various controller components. It does so through a family of "param" methods. These methods allow you to register arbitrary data -- objects and variables -- with the front controller to be retrieved at any time in the dispatch chain. These values are passed on to the router, dispatcher, and action controllers. The methods include:

- setParam($name, $value) allows you to set a single parameter of `$name` with value `$value`.

- setParams(array $params) allows you to set multiple parameters at once using an associative array.

- getParam($name) allows you to retrieve a single parameter at a time, using `$name` as the identifier.

- getParams() allows you to retrieve the entire list of parameters at once.

- clearParams() allows you to clear a single parameter (by passing a string identifier), multiple named parameters (by passing an array of string identifiers), or the entire parameter stack (by passing nothing).

There are several pre-defined parameters that may be set that have specific uses in the dispatch chain:

- useDefaultControllerAlways is used to hint to the dispatcher to use the default controller in the default module for any request that is not dispatchable (i.e., the module, controller, and/or action do not exist). By default, this is off.

  See MVC Exceptions You May Encounter for more detailed information on using this setting.

- disableOutputBuffering is used to hint to the dispatcher that it should not use output buffering to capture output generated by action controllers. By default, the dispatcher captures any output and appends it to the response object body content.

- noViewRenderer is used to disable the ViewRenderer. Set this parameter to `TRUE` to disable it.

- noErrorHandler is used to disable the Error Handler plugin. Set this parameter to `TRUE` to disable it.

## Extending the Front Controller

To extend the Front Controller, at the very minimum you will need to override the getInstance() method:

    class My_Controller_Front extends Zend_Controller_Front
    {
        public static function getInstance()
        {
            if (null === self::$_instance) {
                self::$_instance = new self();
            }

            return self::$_instance;
        }
    }

Overriding the getInstance() method ensures that subsequent calls to Zend_Controller_Front::getInstance() will return an instance of your new subclass instead of a Zend_Controller_Front instance -- this is particularly useful for some of the alternate routers and view helpers.

Typically, you will not need to subclass the front controller unless you need to add new functionality (for instance, a plugin autoloader, or a way to specify action helper paths). Some points where you may want to alter behaviour may include modifying how controller directories are stored, or what default router or dispatcher are used.