Previous Next

Plugins

Introduction

The controller architecture includes a plugin system that allows user code to be called when certain events occur in the controller process lifetime. The front controller uses a plugin broker as a registry for user plugins, and the plugin broker ensures that event methods are called on each plugin registered with the front controller.

The event methods are defined in the abstract class Zend_Controller_Plugin_Abstract, from which user plugin classes inherit:

  • routeStartup() is called before Zend_Controller_Front calls on the router to evaluate the request against the registered routes.

  • routeShutdown() is called after the router finishes routing the request.

  • dispatchLoopStartup() is called before Zend_Controller_Front enters its dispatch loop.

  • preDispatch() is called before an action is dispatched by the dispatcher. This callback allows for proxy or filter behavior. By altering the request and resetting its dispatched flag (via Zend_Controller_Request_Abstract::setDispatched(false)), the current action may be skipped and/or replaced.

  • postDispatch() is called after an action is dispatched by the dispatcher. This callback allows for proxy or filter behavior. By altering the request and resetting its dispatched flag (via Zend_Controller_Request_Abstract::setDispatched(false)), a new action may be specified for dispatching.

  • dispatchLoopShutdown() is called after Zend_Controller_Front exits its dispatch loop.

Writing Plugins

In order to write a plugin class, simply include and extend the abstract class Zend_Controller_Plugin_Abstract:

class MyPlugin extends Zend_Controller_Plugin_Abstract
{
    // ...
}

None of the methods of Zend_Controller_Plugin_Abstract are abstract, and this means that plugin classes are not forced to implement any of the available event methods listed above. Plugin writers may implement only those methods required by their particular needs.

Zend_Controller_Plugin_Abstract also makes the request and response objects available to controller plugins via the getRequest() and getResponse() methods, respectively.

Using Plugins

Plugin classes are registered with Zend_Controller_Front::registerPlugin(), and may be registered at any time. The following snippet illustrates how a plugin may be used in the controller chain:

class MyPlugin extends Zend_Controller_Plugin_Abstract
{
    public function routeStartup(Zend_Controller_Request_Abstract $request)
    {
        $this->getResponse(
             ->appendBody("

routeStartup() called

\n"); } public function routeShutdown(Zend_Controller_Request_Abstract $request) { $this->getResponse( ->appendBody("

routeShutdown() called

\n"); } public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request) { $this->getResponse( ->appendBody("

dispatchLoopStartup() called

\n"); } public function preDispatch(Zend_Controller_Request_Abstract $request) { $this->getResponse() ->appendBody("

preDispatch() called

\n"); } public function postDispatch(Zend_Controller_Request_Abstract $request) { $this->getResponse() ->appendBody("

postDispatch() called

\n"); } public function dispatchLoopShutdown() { $this->getResponse() ->appendBody("

dispatchLoopShutdown() called

\n"); } } $front = Zend_Controller_Front::getInstance(); $front->setControllerDirectory('/path/to/controllers') ->setRouter(new Zend_Controller_Router_Rewrite()) ->registerPlugin(new MyPlugin()); $front->dispatch();

Assuming that no actions called emit any output, and only one action is called, the functionality of the above plugin would still create the following output:

routeStartup() called

routeShutdown() called

dispatchLoopStartup() called

preDispatch() called

postDispatch() called

dispatchLoopShutdown() called

Note:

Plugins may be registered at any time during the front controller execution. However, if an event has passed for which the plugin has a registered event method, that method will not be triggered.

Retrieving and Manipulating Plugins

On occasion, you may need to unregister or retrieve a plugin. The following methods of the front controller allow you to do so:

  • getPlugin($class) allows you to retrieve a plugin by class name. If no plugins match, it returns false. If more than one plugin of that class is registered, it returns an array.

  • getPlugins() retrieves the entire plugin stack.

  • unregisterPlugin($plugin) allows you to remove a plugin from the stack. You may pass a plugin object, or the class name of the plugin you wish to unregister. If you pass the class name, any plugins of that class will be removed.

Plugins Included in the Standard Distribution

Zend Framework includes a plugin for error handling in its standard distribution.

ActionStack

The ActionStack plugin allows you to manage a stack of requests, and operates as a postDispatch plugin. If a forward (i.e., a call to another action) is already detected in the current request object, it does nothing. However, if not, it checks its stack and pulls the topmost item off it and forwards to the action specified in that request. The stack is processed in LIFO order.

You can retrieve the plugin from the front controller at any time using Zend_Controller_Front::getPlugin('Zend_Controller_Plugin_ActionStack'). Once you have the plugin object, there are a variety of mechanisms you can use to manipulate it.

  • getRegistry() and setRegistry(). Internally, ActionStack uses a Zend_Registry instance to store the stack. You can substitute a different registry instance or retrieve it with these accessors.

  • getRegistryKey() and setRegistryKey(). These can be used to indicate which registry key to use when pulling the stack. Default value is 'Zend_Controller_Plugin_ActionStack'.

  • getStack() allows you to retrieve the stack of actions in its entirety.

  • pushStack() and popStack() allow you to add to and pull from the stack, respectively. pushStack() accepts a request object.

An additional method, forward(), expects a request object, and sets the state of the current request object in the front controller to the state of the provided request object, and markes it as undispatched (forcing another iteration of the dispatch loop).

Zend_Controller_Plugin_ErrorHandler

Zend_Controller_Plugin_ErrorHandler provides a drop-in plugin for handling exceptions thrown by your application, including those resulting from missing controllers or actions; it is an alternative to the methods listed in the MVC Exceptions section.

The primary targets of the plugin are:

  • Intercept exceptions raised due to missing controllers or action methods

  • Intercept exceptions raised within action controllers

In other words, the ErrorHandler plugin is designed to handle HTTP 404-type errors (page missing) and 500-type errors (internal error). It is not intended to catch exceptions raised in other plugins or routing.

By default, Zend_Controller_Plugin_ErrorHandler will forward to ErrorController::errorAction() in the default module. You may set alternate values for these by using the various accessors available to the plugin:

  • setErrorHandlerModule() sets the controller module to use.

  • setErrorHandlerController() sets the controller to use.

  • setErrorHandlerAction() sets the controller action to use.

  • setErrorHandler() takes an associative array, which may contain any of the keys 'module', 'controller', or 'action', with which it will set the appropriate values.

Additionally, you may pass an optional associative array to the constructor, which will then proxy to setErrorHandler().

Zend_Controller_Plugin_ErrorHandler registers a postDispatch() hook and checks for exceptions registered in the response object. If any are found, it attempts to forward to the registered error handler action.

If an exception occurs dispatching the error handler, the plugin will tell the front controller to throw exceptions, and rethrow the last exception registered with the response object.

Using the ErrorHandler as a 404 Handler

Since the ErrorHandler plugin captures not only application errors, but also errors in the controller chain arising from missing controller classes and/or action methods, it can be used as a 404 handler. To do so, you will need to have your error controller check the exception type.

Exceptions captured are logged in an object registered in the request. To retrieve it, use Zend_Controller_Action::_getParam('error_handler'):

class ErrorController extends Zend_Controller_Action
{
    public function errorAction()
    {
        $errors = $this->_getParam('error_handler');
    }
}

Once you have the error object, you can get the type via $errors->type. It will be one of the following:

  • Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER, indicating the controller was not found.

  • Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION, indicating the requested action was not found.

  • Zend_Controller_Plugin_ErrorHandler::EXCEPTION_OTHER, indicating other exceptions.

You can then test for either of the first two types, and, if so, indicate a 404 page:

class ErrorController extends Zend_Controller_Action
{
    public function errorAction()
    {
        $errors = $this->_getParam('error_handler');

        switch ($errors->type) {
            case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER:
            case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION:
                // 404 error -- controller or action not found
                $this->getResponse()
                     ->setRawHeader('HTTP/1.1 404 Not Found');

                // ... get some output to display...
                break;
            default:
                // application error; display error page, but don't
                // change status code
                break;
        }
    }
}

Finally, you can retrieve the exception that triggered the error handler by grabbing the exception property of the error_handler object:

public function errorAction()
{
        $errors = $this->_getParam('error_handler');


        switch ($errors->type) {
            case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER:
            case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION:
                // 404 error -- controller or action not found
                $this->getResponse()
                     ->setRawHeader('HTTP/1.1 404 Not Found');

                // ... get some output to display...
                break;
            default:
                // application error; display error page, but don't change
                // status code

                // ...

                // Log the exception:
                $exception = $errors->exception;
                $log = new Zend_Log(
                    new Zend_Log_Writer_Stream(
                        '/tmp/applicationException.log'
                    )
                );
                $log->debug($exception->getMessage() . "\n" .
                            $exception->getTraceAsString());
                break;
        }
}

Handling Previously Rendered Output

If you dispatch multiple actions in a request, or if your action makes multiple calls to render(), its possible that the response object already has content stored within it. This can lead to rendering a mixture of expected content and error content.

If you wish to render errors inline in such pages, no changes will be necessary. If you do not wish to render such content, you should clear the response body prior to rendering any views:

$this->getResponse()->clearBody();

Plugin Usage Examples

Example #1 Standard usage

$front = Zend_Controller_Front::getInstance();
$front->registerPlugin(new Zend_Controller_Plugin_ErrorHandler());

Example #2 Setting a different error handler

$front = Zend_Controller_Front::getInstance();
$front->registerPlugin(new Zend_Controller_Plugin_ErrorHandler(array(
    'module'     => 'mystuff',
    'controller' => 'static',
    'action'     => 'error'
)));

Example #3 Using accessors

$plugin = new Zend_Controller_Plugin_ErrorHandler();
$plugin->setErrorHandlerModule('mystuff')
       ->setErrorHandlerController('static')
       ->setErrorHandlerAction('error');

$front = Zend_Controller_Front::getInstance();
$front->registerPlugin($plugin);

Error Controller Example

In order to use the Error Handler plugin, you need an error controller. Below is a simple example.

class ErrorController extends Zend_Controller_Action
{
    public function errorAction()
    {
        $errors = $this->_getParam('error_handler');

        switch ($errors->type) {
            case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER:
            case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION:
                // 404 error -- controller or action not found
                $this->getResponse()->setRawHeader('HTTP/1.1 404 Not Found');

                $content =<<Error!

The page you requested was not found.

EOH; break; default: // application error $content =<<Error!

An unexpected error occurred. Please try again later.

EOH; break; } // Clear previous content $this->getResponse()->clearBody(); $this->view->content = $content; } }
Previous Next
Introduction to Zend Framework
Overview
Installation
Zend_Acl
Introduction
Refining Access Controls
Advanced Usage
Zend_Amf
Introduction
Zend_Amf_Server
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_Config
Introduction
Theory of Operation
Zend_Config_Ini
Zend_Config_Xml
Zend_Config_Writer
Zend_Config_Writer
Zend_Console_Getopt
Introduction to Getopt
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 to Gdata
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
Zend_Http_Client - 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
JSON Objects
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
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_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 the PDF document.
Document pages.
Drawing
Document Info and Metadata.
Zend_Pdf module usage example
Zend_ProgressBar
Zend_ProgressBar
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_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_Test
Introduction
Zend_Test_PHPUnit
Zend_Text
Zend_Text_Figlet
Zend_Text_Table
Zend_TimeSync
Introduction
Working with Zend_TimeSync
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
Zend_Version
Reading the Zend Framework Version
Zend_View
Introduction
Controller Scripts
View Scripts
View Helpers
Zend_View_Abstract
Zend_Wildfire
Zend_Wildfire
Zend_XmlRpc
Introduction
Zend_XmlRpc_Client
Zend_XmlRpc_Server
Zend Framework Requirements
PHP Version
PHP Extensions
Zend Framework Components
Zend Framework Dependencies
Zend Framework Coding Standard for PHP
Overview
PHP File Formatting
Naming Conventions
Coding Style
Zend Framework Performance Guide
Introduction
Class Loading
Internationalization (i18n) and Localization (l10n)
View Rendering
Copyright Information