Previous Next

Action Controllers

Introduction

Zend_Controller_Action is an abstract class you may use for implementing Action Controllers for use with the Front Controller when building a website based on the Model-View-Controller (MVC) pattern.

To use Zend_Controller_Action, you will need to subclass it in your actual action controller classes (or subclass it to create your own base class for action controllers). The most basic operation is to subclass it, and create action methods that correspond to the various actions you wish the controller to handle for your site. Zend_Controller's routing and dispatch handling will autodiscover any methods ending in 'Action' in your class as potential controller actions.

For example, let's say your class is defined as follows:

class FooController extends Zend_Controller_Action
{
    public function barAction()
    {
        // do something
    }

    public function bazAction()
    {
        // do something
    }
}

The above FooController class (controller foo) defines two actions, bar and baz.

There's much more that can be accomplished than this, such as custom initialization actions, default actions to call should no action (or an invalid action) be specified, pre- and post-dispatch hooks, and a variety of helper methods. This chapter serves as an overview of the action controller functionality

Note: Default Behaviour

By default, the front controller enables the ViewRenderer action helper. This helper takes care of injecting the view object into the controller, as well as automatically rendering views. You may disable it within your action controller via one of the following methods:

class FooController extends Zend_Controller_Action
{
    public function init()
    {
        // Local to this controller only; affects all actions,
        // as loaded in init:
        $this->_helper->viewRenderer->setNoRender(true);

        // Globally:
        $this->_helper->removeHelper('viewRenderer');

        // Also globally, but would need to be in conjunction with the
        // local version in order to propagate for this controller:
        Zend_Controller_Front::getInstance()
            ->setParam('noViewRenderer', true);
    }
}

initView(), getViewScript(), render(), and renderScript() each proxy to the ViewRenderer unless the helper is not in the helper broker or the noViewRenderer flag has been set.

You can also simply disable rendering for an individual view by setting the ViewRenderer's noRender flag:

class FooController extends Zend_Controller_Action
{
    public function barAction()
    {
        // disable autorendering for this action only:
        $this->_helper->viewRenderer->setNoRender();
    }
}

The primary reasons to disable the ViewRenderer are if you simply do not need a view object or if you are not rendering via view scripts (for instance, when using an action controller to serve web service protocols such as SOAP, XML-RPC, or REST). In most cases, you will never need to globally disable the ViewRenderer, only selectively within individual controllers or actions.

Object Initialization

While you can always override the action controller's constructor, we do not recommend this. Zend_Controller_Action::__construct() performs some important tasks, such as registering the request and response objects, as well as any custom invocation arguments passed in from the front controller. If you must override the constructor, be sure to call parent::__construct($request, $response, $invokeArgs).

The more appropriate way to customize instantiation is to use the init() method, which is called as the last task of __construct(). For example, if you want to connect to a database at instantiation:

class FooController extends Zend_Controller_Action
{
    public function init()
    {
        $this->db = Zend_Db::factory('Pdo_Mysql', array(
            'host'     => 'myhost',
            'username' => 'user',
            'password' => 'XXXXXXX',
            'dbname'   => 'website'
        ));
    }
}

Pre- and Post-Dispatch Hooks

Zend_Controller_Action specifies two methods that may be called to bookend a requested action, preDispatch() and postDispatch(). These can be useful in a variety of ways: verifying authentication and ACL's prior to running an action (by calling _forward() in preDispatch(), the action will be skipped), for instance, or placing generated content in a sitewide template ( postDispatch()).

Note: Usage of init() vs. preDispatch()

In the previous section, we introduced the init() method, and in this section, the preDispatch() method. What is the difference between them, and what actions would you take in each?

The init() method is primarily intended for extending the constructor. Typically, your constructor should simply set object state, and not perform much logic. This might include initializing resources used in the controller (such as models, configuration objects, etc.), or assigning values retrieved from the front controller, bootstrap, or a registry.

The preDispatch() method can also be used to set object or environmental (e.g., view, action helper, etc.) state, but its primary purpose is to make decisions about whether or not the requested action should be dispatched. If not, you should then _forward() to another action, or throw an exception.

Note: _forward() actually will not work correctly when executed from init(), which is a formalization of the intentions of the two methods.

Accessors

A number of objects and variables are registered with the object, and each has accessor methods.

  • Request Object: getRequest() may be used to retrieve the request object used to call the action.

  • Response Object: getResponse() may be used to retrieve the response object aggregating the final response. Some typical calls might look like:

    $this->getResponse()->setHeader('Content-Type', 'text/xml');
    $this->getResponse()->appendBody($content);
  • Invocation Arguments: the front controller may push parameters into the router, dispatcher, and action controller. To retrieve these, use getInvokeArg($key); alternatively, fetch the entire list using getInvokeArgs().

  • Request parameters: The request object aggregates request parameters, such as any _GET or _POST parameters, or user parameters specified in the URL's path information. To retrieve these, use _getParam($key) or _getAllParams(). You may also set request parameters using _setParam(); this is useful when forwarding to additional actions.

    To test whether or not a parameter exists (useful for logical branching), use _hasParam($key).

    Note:

    _getParam() may take an optional second argument containing a default value to use if the parameter is not set or is empty. Using it eliminates the need to call _hasParam() prior to retrieving a value:

    // Use default value of 1 if id is not set
    $id = $this->_getParam('id', 1);
    
    // Instead of:
    if ($this->_hasParam('id') {
        $id = $this->_getParam('id');
    } else {
        $id = 1;
    }

View Integration

Note: Default View Integration is Via the ViewRenderer

The content in this section is only valid when you have explicitly disabled the ViewRenderer. Otherwise, you can safely skip over this section.

Zend_Controller_Action provides a rudimentary and flexible mechanism for view integration. Two methods accomplish this, initView() and render(); the former method lazy-loads the $view public property, and the latter renders a view based on the current requested action, using the directory hierarchy to determine the script path.

View Initialization

initView() initializes the view object. render() calls initView() in order to retrieve the view object, but it may be initialized at any time; by default it populates the $view property with a Zend_View object, but any class implementing Zend_View_Interface may be used. If $view is already initialized, it simply returns that property.

The default implementation makes the following assumption of the directory structure:

applicationOrModule/
    controllers/
        IndexController.php
    views/
        scripts/
            index/
                index.phtml
        helpers/
        filters/

In other words, view scripts are assumed to be in the /views/scripts/ subdirectory, and the /views/ subdirectory is assumed to contain sibling functionality (helpers, filters). When determining the view script name and path, the /views/scripts/ directory will be used as the base path, with directories named after the individual controllers providing a hierarchy of view scripts.

Rendering Views

render() has the following signature:

string render(string $action = null,
              string $name = null,
              bool $noController = false);

render() renders a view script. If no arguments are passed, it assumes that the script requested is [controller]/[action].phtml (where .phtml is the value of the $viewSuffix property). Passing a value for $action will render that template in the /[controller]/ subdirectory. To override using the /[controller]/ subdirectory, pass a TRUE value for $noController. Finally, templates are rendered into the response object; if you wish to render to a specific named segment in the response object, pass a value to $name.

Note:

Since controller and action names may contain word delimiter characters such as '_', '.', and '-', render() normalizes these to '-' when determining the script name. Internally, it uses the dispatcher's word and path delimiters to do this normalization. Thus, a request to /foo.bar/baz-bat will render the script foo-bar/baz-bat.phtml. If your action method contains camelCasing, please remember that this will result in '-' separated words when determining the view script file name.

Some examples:

class MyController extends Zend_Controller_Action
{
    public function fooAction()
    {
        // Renders my/foo.phtml
        $this->render();

        // Renders my/bar.phtml
        $this->render('bar');

        // Renders baz.phtml
        $this->render('baz', null, true);

        // Renders my/login.phtml to the 'form' segment of the
        // response object
        $this->render('login', 'form');

        // Renders site.phtml to the 'page' segment of the response
        // object; does not use the 'my/' subirectory
        $this->render('site', 'page', true);
    }

    public function bazBatAction()
    {
        // Renders my/baz-bat.phtml
        $this->render();
    }
}

Utility Methods

Besides the accessors and view integration methods, Zend_Controller_Action has several utility methods for performing common tasks from within your action methods (or from pre- and post-dispatch).

  • _forward($action, $controller = null, $module = null, array $params = null): perform another action. If called in preDispatch(), the currently requested action will be skipped in favor of the new one. Otherwise, after the current action is processed, the action requested in _forward() will be executed.

  • _redirect($url, array $options = array()): redirect to another location. This method takes a URL and an optional set of options. By default, it performs an HTTP 302 redirect.

    The options may include one or more of the following:

    • exit: whether or not to exit immediately. If requested, it will cleanly close any open sessions and perform the redirect.

      You may set this option globally within the controller using the setRedirectExit() accessor.

    • prependBase: whether or not to prepend the base URL registered with the request object to the URL provided.

      You may set this option globally within the controller using the setRedirectPrependBase() accessor.

    • code: what HTTP code to utilize in the redirect. By default, an HTTP 302 is utilized; any code between 301 and 306 may be used.

      You may set this option globally within the controller using the setRedirectCode() accessor.

Subclassing the Action Controller

By design, Zend_Controller_Action must be subclassed in order to create an action controller. At the minimum, you will need to define action methods that the controller may call.

Besides creating useful functionality for your web applications, you may also find that you're repeating much of the same setup or utility methods in your various controllers; if so, creating a common base controller class that extends Zend_Controller_Action could solve such redundancy.

Example #1 Handling Non-Existent Actions

If a request to a controller is made that includes an undefined action method, Zend_Controller_Action::__call() will be invoked. __call() is, of course, PHP's magic method for method overloading.

By default, this method throws a Zend_Controller_Action_Exception indicating the requested method was not found in the controller. If the method requested ends in 'Action', the assumption is that an action was requested and does not exist; such errors result in an exception with a code of 404. All other methods result in an exception with a code of 500. This allows you to easily differentiate between page not found and application errors in your error handler.

You should override this functionality if you wish to perform other operations. For instance, if you wish to display an error message, you might write something like this:

class MyController extends Zend_Controller_Action
{
    public function __call($method, $args)
    {
        if ('Action' == substr($method, -6)) {
            // If the action method was not found, render the error
            // template
            return $this->render('error');
        }

        // all other methods throw an exception
        throw new Exception('Invalid method "'
                            . $method
                            . '" called',
                            500);
    }
}

Another possibility is that you may want to forward on to a default controller page:

class MyController extends Zend_Controller_Action
{
    public function indexAction()
    {
        $this->render();
    }

    public function __call($method, $args)
    {
        if ('Action' == substr($method, -6)) {
            // If the action method was not found, forward to the
            // index action
            return $this->_forward('index');
        }

        // all other methods throw an exception
        throw new Exception('Invalid method "'
                            . $method
                            . '" called',
                            500);
    }
}

Besides overriding __call(), each of the initialization, utility, accessor, view, and dispatch hook methods mentioned previously in this chapter may be overridden in order to customize your controllers. As an example, if you are storing your view object in a registry, you may want to modify your initView() method with code resembling the following:

abstract class My_Base_Controller extends Zend_Controller_Action
{
    public function initView()
    {
        if (null === $this->view) {
            if (Zend_Registry::isRegistered('view')) {
                $this->view = Zend_Registry::get('view');
            } else {
                $this->view = new Zend_View();
                $this->view->setBasePath(dirname(__FILE__) . '/../views');
            }
        }

        return $this->view;
    }
}

Hopefully, from the information in this chapter, you can see the flexibility of this particular component and how you can shape it to your application's or site's needs.

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_Db_Table_Definition
Zend_Debug
Dumping Variables
Zend_Dojo
Introduction
Zend_Dojo_Data: dojo.data Envelopes
Dojo View Helpers
Dojo Form Elements and Decorators
Zend_Dojo build layer support
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_Feed_Reader
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
Migrating from Previous Versions
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
Migrating from previous versions
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
API overview
Usage Scenarios
Tools
Object oriented access to the LDAP tree using Zend_Ldap_Node
Getting information from the LDAP server
Serializing LDAP data to and from LDIF
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
Migrating from Previous Versions
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
Interactive Features
Document Info and Metadata
Zend_Pdf module usage example
Zend_ProgressBar
Zend_ProgressBar
Zend_Queue
Introduction
Example usage
Framework
Adapters
Customizing Zend_Queue
Stomp
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_Amazon_Sqs
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_Test_PHPUnit_Db
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
Extending and Configuring Zend_Tool_Framework
Zend_Tool_Project
Introduction
Create A Project
Zend Tool Project Providers
Zend_Translate
Introduction
Adapters for Zend_Translate
Using Translation Adapters
Creating source files
Additional features for translation
Plural notations for Translation
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 Documentation Standard
Overview
Documentation File Formatting
Recommendations
Recommended Project Structure for Zend Framework MVC Applications
Overview
Recommended Project Directory Structure
Module Structure
Rewrite Configuration Guide
Zend Framework Performance Guide
Introduction
Class Loading
Zend_Db Performance
Internationalization (i18n) and Localization (l10n)
View Rendering
Copyright Information