Previous Next

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.

Note: 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/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');

Note:

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.

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.

  • (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)DefaultAction() 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.

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

Previous Next
Introduction to Zend Framework
Overview
Installation
Zend_Acl
Introduction
Refining Access Controls
Advanced Usage
Zend_Amf
Introduction
Zend_Amf_Server
Zend_Application
Introduction
Zend_Application Quick Start
Theory of Operation
Examples
Core Functionality
Available Resource Plugins
Zend_Auth
Introduction
Database Table Authentication
Digest Authentication
HTTP Authentication Adapter
LDAP Authentication
Open ID Authentication
Zend_Cache
Introduction
The Theory of Caching
Zend_Cache Frontends
Zend_Cache Backends
Zend_Captcha
Introduction
Captcha Operation
CAPTCHA Adapters
Zend_CodeGenerator
Introduction
Zend_CodeGenerator Examples
Zend_CodeGenerator Reference
Zend_Config
Introduction
Theory of Operation
Zend_Config_Ini
Zend_Config_Xml
Zend_Config_Writer
Zend_Config_Writer
Zend_Console_Getopt
Introduction
Declaring Getopt Rules
Fetching Options and Arguments
Configuring Zend_Console_Getopt
Zend_Controller
Zend_Controller Quick Start
Zend_Controller Basics
The Front Controller
The Request Object
The Standard Router
The Dispatcher
Action Controllers
Action Helpers
The Response Object
Plugins
Using a Conventional Modular Directory Structure
MVC Exceptions
Migrating from Previous Versions
Zend_Currency
Introduction to Zend_Currency
How to Work with Currencies
Migrating from Previous Versions
Zend_Date
Introduction
Theory of Operation
Basic Methods
Zend_Date API Overview
Creation of Dates
Constants for General Date Functions
Working Examples
Zend_Db
Zend_Db_Adapter
Zend_Db_Statement
Zend_Db_Profiler
Zend_Db_Select
Zend_Db_Table
Zend_Db_Table_Row
Zend_Db_Table_Rowset
Zend_Db_Table Relationships
Zend_Debug
Dumping Variables
Zend_Dojo
Introduction
Zend_Dojo_Data: dojo.data Envelopes
Dojo View Helpers
Dojo Form Elements and Decorators
Zend_Dom
Introduction
Zend_Dom_Query
Zend_Exception
Using Exceptions
Zend_Feed
Introduction
Importing Feeds
Retrieving Feeds from Web Pages
Consuming an RSS Feed
Consuming an Atom Feed
Consuming a Single Atom Entry
Modifying Feed and Entry structures
Custom Feed and Entry Classes
Zend_File
Zend_File_Transfer
Validators for Zend_File_Transfer
Filters for Zend_File_Transfer
Migrating from previous versions
Zend_Filter
Introduction
Standard Filter Classes
Filter Chains
Writing Filters
Zend_Filter_Input
Zend_Filter_Inflector
Zend_Form
Zend_Form
Zend_Form Quick Start
Creating Form Elements Using Zend_Form_Element
Creating Forms Using Zend_Form
Creating Custom Form Markup Using Zend_Form_Decorator
Standard Form Elements Shipped With Zend Framework
Standard Form Decorators Shipped With Zend Framework
Internationalization of Zend_Form
Advanced Zend_Form Usage
Zend_Gdata
Introduction
Authenticating with AuthSub
Using the Book Search Data API
Authenticating with ClientLogin
Using Google Calendar
Using Google Documents List Data API
Using Google Health
Using Google Spreadsheets
Using Google Apps Provisioning
Using Google Base
Using Picasa Web Albums
Using the YouTube Data API
Catching Gdata Exceptions
Zend_Http
Introduction
Zend_Http_Client - Advanced Usage
Zend_Http_Client - Connection Adapters
Zend_Http_Cookie and Zend_Http_CookieJar
Zend_Http_Response
Zend_InfoCard
Introduction
Zend_Json
Introduction
Basic Usage
Advanced Usage of Zend_Json
XML to JSON conversion
Zend_Json_Server - JSON-RPC server
Zend_Layout
Introduction
Zend_Layout Quick Start
Zend_Layout Configuration Options
Zend_Layout Advanced Usage
Zend_Ldap
Introduction
Zend_Loader
Loading Files and Classes Dynamically
The Autoloader
Resource Autoloaders
Loading Plugins
Zend_Locale
Introduction
Using Zend_Locale
Normalization and Localization
Working with Dates and Times
Supported locales
Migrating from previous versions
Zend_Log
Overview
Writers
Formatters
Filters
Zend_Mail
Introduction
Sending via SMTP
Sending Multiple Mails per SMTP Connection
Using Different Transports
HTML E-Mail
Attachments
Adding Recipients
Controlling the MIME Boundary
Additional Headers
Character Sets
Encoding
SMTP Authentication
Securing SMTP Transport
Reading Mail Messages
Zend_Measure
Introduction
Creation of Measurements
Outputting measurements
Manipulating Measurements
Types of measurements
Zend_Memory
Overview
Memory Manager
Memory Objects
Zend_Mime
Zend_Mime
Zend_Mime_Message
Zend_Mime_Part
Zend_Navigation
Introduction
Pages
Containers
Zend_OpenId
Introduction
Zend_OpenId_Consumer Basics
Zend_OpenId_Provider
Zend_Paginator
Introduction
Usage
Configuration
Advanced usage
Zend_Pdf
Introduction
Creating and Loading PDF Documents
Save Changes to PDF Documents
Working with Pages
Drawing
Document Info and Metadata.
Zend_Pdf module usage example
Zend_ProgressBar
Zend_ProgressBar
Zend_Reflection
Introduction
Zend_Reflection Examples
Zend_Reflection Reference
Zend_Registry
Using the Registry
Zend_Rest
Introduction
Zend_Rest_Client
Zend_Rest_Server
Zend_Search_Lucene
Overview
Building Indexes
Searching an Index
Query Language
Query Construction API
Character Set
Extensibility
Interoperating with Java Lucene
Advanced
Best Practices
Zend_Server
Introduction
Zend_Server_Reflection
Zend_Service
Introduction
Zend_Service_Akismet
Zend_Service_Amazon
Zend_Service_Amazon_Ec2
Zend_Service_Amazon_Ec2: Instances
Zend_Service_Amazon_Ec2: Windows Instances
Zend_Service_Amazon_Ec2: Reserved Instances
Zend_Service_Amazon_Ec2: CloudWatch Monitoring
Zend_Service_Amazon_Ec2: Amazon Machine Images (AMI)
Zend_Service_Amazon_Ec2: Elastic Block Stroage (EBS)
Zend_Service_Amazon_Ec2: Elastic IP Addresses
Zend_Service_Amazon_Ec2: Keypairs
Zend_Service_Amazon_Ec2: Regions and Availability Zones
Zend_Service_Amazon_Ec2: Security Groups
Zend_Service_Amazon_S3
Zend_Service_Audioscrobbler
Zend_Service_Delicious
Zend_Service_Flickr
Zend_Service_Nirvanix
Zend_Service_ReCaptcha
Zend_Service_Simpy
Introduction
Zend_Service_StrikeIron
Zend_Service_StrikeIron: Bundled Services
Zend_Service_StrikeIron: Advanced Uses
Zend_Service_Technorati
Zend_Service_Twitter
Zend_Service_Yahoo
Zend_Session
Introduction
Basic Usage
Advanced Usage
Global Session Management
Zend_Session_SaveHandler_DbTable
Zend_Soap
Zend_Soap_Server
Zend_Soap_Client
WSDL Accessor
AutoDiscovery
Zend_Tag
Introduction
Zend_Tag_Cloud
Zend_Test
Introduction
Zend_Test_PHPUnit
Zend_Text
Zend_Text_Figlet
Zend_Text_Table
Zend_TimeSync
Introduction
Working with Zend_TimeSync
Zend_Tool_Framework
Introduction
Using the CLI Tool
Architecture
Creating Providers to use with Zend_Tool_Framework
Shipped System Providers
Zend_Tool_Project
Zend_Tool_Project Introduction
Create A Project
Zend Tool Project Providers
Zend_Translate
Introduction
Adapters for Zend_Translate
Using Translation Adapters
Migrating from previous versions
Zend_Uri
Zend_Uri
Zend_Validate
Introduction
Standard Validation Classes
Validator Chains
Writing Validators
Validation Messages
Zend_Version
Getting the Zend Framework Version
Zend_View
Introduction
Controller Scripts
View Scripts
View Helpers
Zend_View_Abstract
Migrating from Previous Versions
Zend_Wildfire
Zend_Wildfire
Zend_XmlRpc
Introduction
Zend_XmlRpc_Client
Zend_XmlRpc_Server
Zend Framework Requirements
Introduction
Zend Framework Coding Standard for PHP
Overview
PHP File Formatting
Naming Conventions
Coding Style
Zend Framework Performance Guide
Introduction
Class Loading
Zend_Db Performance
Internationalization (i18n) and Localization (l10n)
View Rendering
Copyright Information