Chapter 10. Zend_Controller

Table of Contents

10.1. Zend_Controller Quick Start
10.1.1. Introduction
10.1.2. Quick Start Create your filesystem layout Set your document root Create your rewrite rules Create your bootstrap file Create your default action controller Create your view script Create your error controller View the site!
10.2. Zend_Controller Basics
10.3. The Front Controller
10.3.1. Overview
10.3.2. Primary Methods getInstance() setControllerDirectory() and addControllerDirectory addModuleDirectory() and getModuleDirectory() dispatch() run()
10.3.3. Environmental Accessor Methods
10.3.4. Front Controller Parameters
10.3.5. Subclassing the Front Controller
10.4. The Request Object
10.4.1. Introduction
10.4.2. HTTP Requests Accessing Request Data Base Url and Subdirectories Determining the Request Method Detecting AJAX Requests
10.4.3. Subclassing the Request Object
10.5. The Standard Router
10.5.1. Introduction
10.5.2. Using a router
10.5.3. Basic Rewrite Router operation
10.5.4. Default routes
10.5.5. Base URL and subdirectories
10.5.6. Global parameters
10.5.7. Route Types Zend_Controller_Router_Route Variable defaults Variable requirements Zend_Controller_Router_Route_Static Zend_Controller_Router_Route_Regex Zend_Controller_Router_Route_Hostname Hostname routes via Zend_Config
10.5.8. Using Zend_Config with the RewriteRouter
10.5.9. Subclassing the Router
10.6. The Dispatcher
10.6.1. Overview
10.6.2. Subclassing the Dispatcher
10.7. Action Controllers
10.7.1. Introduction
10.7.2. Object initialization
10.7.3. Pre- and Post-Dispatch Hooks
10.7.4. Accessors
10.7.5. View Integration View Initialization Rendering Views
10.7.6. Utility Methods
10.7.7. Subclassing the Action Controller
10.8. Action Helpers
10.8.1. Introduction
10.8.2. Helper Initialization
10.8.3. The Helper Broker
10.8.4. Built-in Action Helpers ActionStack AutoComplete AutoCompletion with Dojo AutoCompletion with Scriptaculous ContextSwitch and AjaxContext Default Contexts Available Creating Custom Contexts Setting Contexts Per Action Initializing Context Switching Additional Functionality AjaxContext Functionality FlashMessenger Introduction Basic Usage Example JSON Redirector Introduction Basic Usage Examples ViewRenderer Introduction API Basic Usage Examples Advanced Usage Examples
10.8.5. Writing Your Own Helpers
10.9. The Response Object
10.9.1. Usage
10.9.2. Manipulating Headers
10.9.3. Named Segments
10.9.4. Testing for Exceptions in the Response Object
10.9.5. Subclassing the Response Object
10.10. Plugins
10.10.1. Introduction
10.10.2. Writing Plugins
10.10.3. Using Plugins
10.10.4. Retrieving and Manipulating Plugins
10.10.5. Plugins Included in the Standard Distribution ActionStack Zend_Controller_Plugin_ErrorHandler Using the ErrorHandler as a 404 Handler Handling Previously Rendered Output Plugin Usage Examples Error Controller Example
10.11. Using a Conventional Modular Directory Structure
10.11.1. Introduction
10.11.2. Specifying Module Controller Directories
10.11.3. Routing to modules
10.11.4. Module or Global Default Controller
10.12. MVC Exceptions
10.12.1. Introduction
10.12.2. How can you handle exceptions?
10.12.3. MVC Exceptions You May Encounter
10.13. Migrating from Previous Versions
10.13.1. Migrating from 1.6.x to 1.7.0 or newer Dispatcher Interface changes
10.13.2. Migrating from 1.5.x to 1.6.0 or newer Dispatcher Interface changes
10.13.3. Migrating from 1.0.x to 1.5.0 or newer
10.13.4. Migrating from 0.9.3 to 1.0.0RC1 or newer
10.13.5. Migrating from 0.9.2 to 0.9.3 or newer
10.13.6. Migrating from 0.6.0 to 0.8.0 or newer
10.13.7. Migrating from 0.2.0 or before to 0.6.0

10.1. Zend_Controller Quick Start

10.1.1. Introduction

Zend_Controller is the heart of Zend Framework's MVC system. MVC stands for Model-View-Controller and is a design pattern targeted at separating application logic from display logic. Zend_Controller_Front implements a Front Controller pattern, in which all requests are intercepted by the front controller and dispatched to individual Action Controllers based on the URL requested.

The Zend_Controller system was built with extensibility in mind, either by subclassing the existing classes, writing new classes that implement the various interfaces and abstract classes that form the foundation of the controller family of classes, or writing plugins or action helpers to augment or manipulate the functionality of the system.

10.1.2. Quick Start

If you need more in-depth information, see the following sections. If you just want to get up and running quickly, read on. Create your filesystem layout

The first step is to create your file system layout. The typical layout is as follows:


     Set your document root

In your web server, point your document root to the html directory of the above file system layout. Create your rewrite rules

Edit the html/.htaccess file above to read as follows:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]


If using IIS 7.0, use the following as your rewrite configuration:

<?xml version="1.0" encoding="UTF-8"?>
                 <rule name="Imported Rule 1" stopProcessing="true">
                     <match url="^.*$" />
                     <conditions logicalGrouping="MatchAny">
                         <add input="{REQUEST_FILENAME}" 
                             matchType="IsFile" pattern="" 
                             ignoreCase="false" />
                         <add input="{REQUEST_FILENAME}" 
                             pattern="" ignoreCase="false" />
                     <action type="None" />
                 <rule name="Imported Rule 2" stopProcessing="true">
                     <match url="^.*$" />
                     <action type="Rewrite" url="index.php" />

The above rules will route requests to existing resources (existing symlinks, non-empty files, or non-empty directories) accordingly, and all other requests to the front controller.

[Note] Note

The above rewrite rules are for Apache; for examples of rewrite rules for other web servers, see the router documentation. Create your bootstrap file

The bootstrap file is the page all requests are routed through -- html/index.php in this case. Open up html/index.php in the editor of your choice and add the following:



This will instantiate and dispatch the front controller, which will route requests to action controllers. Create your default action controller

Before discussing action controllers, you should first understand how requests are routed in Zend Framework. By default, the first segment of a URL path maps to a controller, and the second to an action. For example, given the URL, the path is /roadmap/components, which will map to the controller roadmap and the action components. If no action is provided, the action index is assumed, and if no controller is provided, the controller index is assumed (following the Apache convention that maps a DirectoryIndex automatically).

Zend_Controller's dispatcher then takes the controller value and maps it to a class. By default, it Title-cases the controller name and appends the word Controller. Thus, in our example above, the controller roadmap is mapped to the class RoadmapController.

Similarly, the action value is mapped to a method of the controller class. By default, the value is lower-cased, and the word Action is appended. Thus, in our example above, the action components becomes componentsAction, and the final method called is RoadmapController::componentsAction().

So, moving on, let's now create a default action controller and action method. As noted earlier, the default controller and action called are both index. Open the file application/controllers/IndexController.php, and enter the following:

/** Zend_Controller_Action */
class IndexController extends Zend_Controller_Action
    public function indexAction()


By default, the ViewRenderer action helper is enabled. What this means is that by simply defining an action method and a corresponding view script, you will immediately get content rendered. By default, Zend_View is used as the View layer in the MVC. The ViewRenderer does some magic, and uses the controller name (e.g., index) and the current action name (e.g., index) to determine what template to pull. By default, templates end in the .phtml extension, so this means that, in the above example, the template index/index.phtml will be rendered. Additionally, the ViewRenderer automatically assumes that the directory views at the same level as the controller directory will be the base view directory, and that the actual view scripts will be in the views/scripts/ subdirectory. Thus, the template rendered will be found in application/views/scripts/index/index.phtml. Create your view script

As mentioned in the previous section, view scripts are found in application/views/scripts/; the view script for the default controller and action is in application/views/scripts/index/index.phtml. Create this file, and type in some HTML:

<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>My first Zend Framework App</title>
    <h1>Hello, World!</h1>

     Create your error controller

By default, the error handler plugin is registered. This plugin expects that a controller exists to handle errors. By default, it assumes an ErrorController in the default module with an errorAction method:

class ErrorController extends Zend_Controller_Action
    public function errorAction()


Assuming the already discussed directory layout, this file will go in application/controllers/ErrorController.php. You will also need to create a view script in application/views/scripts/error/error.phtml; sample content might look like:

<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <h1>An error occurred</h1>
    <p>An error occurred; please try again later.</p>

     View the site!

With your first controller and view under your belt, you can now fire up your browser and browse to the site. Assuming is your domain, any of the following URLs will get to the page we've just created:




You're now ready to start creating more controllers and action methods. Congratulations!