7.3. The Front Controller

7.3.1. 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 error handler, simply perform one of the following actions at any point prior to calling dispatch():

<?php
// Unregister the plugin:
$front->unregisterPlugin('Zend_Controller_Plugin_ErrorHandler');

// Or simply disable it:
$front->setParam('noErrorHandler', true);

To disable the view renderer, do one of the following actions point prior to calling dispatch():

<?php
// Remove the action helper from the broker:
Zend_Controller_Action_HelperBroker::removeHelper('viewRenderer');

// Or simply disable it:
$front->setParam('noViewRenderer', true);

In each case, setting the front controller parameter is probably the easiest and fastest method, and also allows your controllers to easily override the setting at any point.

7.3.2. 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:

7.3.2.1. 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.

<?php
$front = Zend_Controller_Front::getInstance();
?>

7.3.2.2. 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/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/directory pairs.

7.3.2.3. 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.

7.3.2.4. 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.

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

7.3.3. 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.

  • (set|get)DefaultControllerName() 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.

  • (set|get)DefaultActionName() 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.

  • (set|get)Request() 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.

  • (set|get)Router() 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).

  • (set|get)BaseUrl() 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.

  • (set|get)Dispatcher() 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.

  • (set|get)Response() 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.

  • (un)registerPlugin() let you register and unregister plugin objects.

  • 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 第 7.12 节 “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.

7.3.4. 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 第 7.12.3 节 “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.

7.3.5. Subclassing the Front Controller

To subclass 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.