Español | English
Update 2010-01-04 - Revision 20081

Chapter 23. Zend_Controller

Table of Contents

23.1. Zend_Controller Quick Start
23.1.1. Introduction
23.1.2. Quick Start
23.1.2.1. Create the Filesystem Layout
23.1.2.2. Set the Document Root
23.1.2.3. Create the Rewrite Rules
23.1.2.4. Create the Bootstrap File
23.1.2.5. Create the Default Action Controller
23.1.2.6. Create the View Script
23.1.2.7. Create the Error Controller
23.1.2.8. View the Site!
23.2. Zend_Controller Basics
23.3. The Front Controller
23.3.1. Overview
23.3.2. Primary Methods
23.3.2.1. getInstance()
23.3.2.2. setControllerDirectory() and addControllerDirectory
23.3.2.3. addModuleDirectory() and getModuleDirectory()
23.3.2.4. dispatch()
23.3.2.5. run()
23.3.3. Environmental Accessor Methods
23.3.4. Front Controller Parameters
23.3.5. Extending the Front Controller
23.4. The Request Object
23.4.1. Introduction
23.4.2. HTTP Requests
23.4.2.1. Accessing Request Data
23.4.2.2. Base Url and Subdirectories
23.4.2.3. Determining the Request Method
23.4.2.4. Detecting AJAX Requests
23.4.3. Subclassing the Request Object
23.5. The Standard Router
23.5.1. Introduction
23.5.2. Using a Router
23.5.3. Basic Rewrite Router Operation
23.5.4. Default Routes
23.5.5. Base URL and Subdirectories
23.5.6. Global Parameters
23.5.7. Route Types
23.5.7.1. Zend_Controller_Router_Route
23.5.7.1.1. Variable Defaults
23.5.7.1.2. Variable Requirements
23.5.7.1.3. Translated segments
23.5.7.2. Zend_Controller_Router_Route_Static
23.5.7.3. Zend_Controller_Router_Route_Regex
23.5.7.4. Zend_Controller_Router_Route_Hostname
23.5.7.5. Zend_Controller_Router_Route_Chain
23.5.7.5.1. Chain Routes via Zend_Config
23.5.7.6. Zend_Rest_Route
23.5.7.6.1. Zend_Rest_Route Usage
23.5.7.6.2. Zend_Rest_Route with Zend_Config_Ini
23.5.7.6.3. Zend_Rest_Controller
23.5.8. Using Zend_Config with the RewriteRouter
23.5.9. Subclassing the Router
23.6. The Dispatcher
23.6.1. Overview
23.6.2. Subclassing the Dispatcher
23.7. Action Controllers
23.7.1. Introduction
23.7.2. Object Initialization
23.7.3. Pre- and Post-Dispatch Hooks
23.7.4. Accessors
23.7.5. View Integration
23.7.5.1. View Initialization
23.7.5.2. Rendering Views
23.7.6. Utility Methods
23.7.7. Subclassing the Action Controller
23.8. Action Helpers
23.8.1. Introduction
23.8.2. Helper Initialization
23.8.3. The Helper Broker
23.8.4. Built-in Action Helpers
23.8.4.1. ActionStack
23.8.4.2. AutoComplete
23.8.4.2.1. AutoCompletion with Dojo
23.8.4.2.2. AutoCompletion with Scriptaculous
23.8.4.3. ContextSwitch and AjaxContext
23.8.4.3.1. Default Contexts Available
23.8.4.3.2. Creating Custom Contexts
23.8.4.3.3. Setting Contexts Per Action
23.8.4.3.4. Initializing Context Switching
23.8.4.3.5. Additional Functionality
23.8.4.3.6. AjaxContext Functionality
23.8.4.4. FlashMessenger
23.8.4.4.1. Introduction
23.8.4.4.2. Basic Usage Example
23.8.4.5. JSON
23.8.4.6. Redirector
23.8.4.6.1. Introduction
23.8.4.6.2. Basic Usage Examples
23.8.4.7. ViewRenderer
23.8.4.7.1. Introduction
23.8.4.7.2. API
23.8.4.7.3. Basic Usage Examples
23.8.4.7.4. Advanced Usage Examples
23.8.5. Writing Your Own Helpers
23.9. The Response Object
23.9.1. Usage
23.9.2. Manipulating Headers
23.9.3. Named Segments
23.9.4. Testing for Exceptions in the Response Object
23.9.5. Subclassing the Response Object
23.10. Plugins
23.10.1. Introduction
23.10.2. Writing Plugins
23.10.3. Using Plugins
23.10.4. Retrieving and Manipulating Plugins
23.10.5. Plugins Included in the Standard Distribution
23.10.5.1. ActionStack
23.10.5.2. Zend_Controller_Plugin_ErrorHandler
23.10.5.2.1. Using the ErrorHandler as a 404 Handler
23.10.5.2.2. Handling Previously Rendered Output
23.10.5.2.3. Plugin Usage Examples
23.10.5.2.4. Error Controller Example
23.10.5.3. Zend_Controller_Plugin_PutHandler
23.11. Using a Conventional Modular Directory Structure
23.11.1. Introduction
23.11.2. Specifying Module Controller Directories
23.11.3. Routing to Modules
23.11.4. Module or Global Default Controller
23.12. MVC Exceptions
23.12.1. Introduction
23.12.2. Handling Exceptions
23.12.3. MVC Exceptions You May Encounter

23.1. Zend_Controller Quick Start

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

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

23.1.2.1. Create the Filesystem Layout

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

application/
    
controllers/
        
IndexController.php
    models
/
    
views/
        
scripts/
            
index/
                
index.phtml
        helpers
/
        
filters/
html/
    .
htaccess
    index
.php

23.1.2.2. Set the Document Root

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

23.1.2.3. Create the Rewrite Rules

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

RewriteEngine On
RewriteCond 
%{REQUEST_FILENAME} -[OR]
RewriteCond %{REQUEST_FILENAME} -[OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule 
^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]
[Note] Learn about mod_rewrite

The above rewrite rules allow access to any file under your virtual host's document root. If there are files you do not want exposed in this way, you may want to be more restrictive in your rules. Go to the Apache website to learn more about mod_rewrite.

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

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
     <system.webServer>
         <rewrite>
             <rules>
                 <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}"
                             matchType="IsDirectory"
                             pattern="" ignoreCase="false" />
                     </conditions>
                     <action type="None" />
                 </rule>
                 <rule name="Imported Rule 2" stopProcessing="true">
                     <match url="^.*$" />
                     <action type="Rewrite" url="index.php" />
                 </rule>
             </rules>
         </rewrite>
     </system.webServer>
</configuration>

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.

23.1.2.4. Create the 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:

Zend_Controller_Front::run('/path/to/app/controllers');

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

23.1.2.5. Create the 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 http://framework.zend.com/roadmap/components, 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.

23.1.2.6. Create the 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"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"
>
<
html>
<
head>
  <
meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <
title>My first Zend Framework App</title>
</
head>
<
body>
    <
h1>HelloWorld!</h1>
</
body>
</
html>

23.1.2.7. Create the 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"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"
>
<
html>
<
head>
  <
meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <
title>Error</title>
</
head>
<
body>
    <
h1>An error occurred</h1>
    <
p>An error occurredplease try again later.</p>
</
body>
</
html>

23.1.2.8. 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 example.com is your domain, any of the following URLs will get to the page we've just created:

  • http://example.com/

  • http://example.com/index

  • http://example.com/index/index

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