7.10. Plugins

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

7.10.2. Writing Plugins

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

<?php
require_once 'Zend/Controller/Plugin/Abstract.php';

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.

7.10.3. 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:

<?php
require_once 'Zend/Controller/Front.php';
require_once 'Zend/Controller/Router.php';
require_once 'Zend/Controller/Plugin/Abstract.php';

class MyPlugin extends Zend_Controller_Plugin_Abstract
{
    public function routeStartup()
    {
        $this->getResponse()->appendBody("<p>routeStartup() called</p>\n");
    }

    public function routeShutdown($request)
    {
        $this->getResponse()->appendBody("<p>routeShutdown() called</p>\n");
    }

    public function dispatchLoopStartup($request)
    {
        $this->getResponse()->appendBody("<p>dispatchLoopStartup() called</p>\n");
    }

    public function preDispatch($request)
    {
        $this->getResponse()->appendBody("<p>preDispatch() called</p>\n");
    }

    public function postDispatch($request)
    {
        $this->getResponse()->appendBody("<p>postDispatch() called</p>\n");
    }

    public function dispatchLoopShutdown()
    {
        $this->getResponse()->appendBody("<p>dispatchLoopShutdown() called</p>\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:

<p>routeStartup() called</p>
<p>routeShutdown() called</p>
<p>dispatchLoopStartup() called</p>
<p>preDispatch() called</p>
<p>postDispatch() called</p>
<p>dispatchLoopShutdown() called</p>
[Opmerking] Opmerking
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.

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

7.10.5. Plugins Included in the Standard Distribution

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

7.10.5.1. Zend_Controller_Plugins_ErrorHandler

Zend_Controller_Plugins_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_Plugins_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.

7.10.5.1.1. 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'):

<?php
class ErrorController extends Zend_Controller_Action
{
    public function errorAction()
    {
        $errors = $this->_getRequest('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:

<?php
class ErrorController extends Zend_Controller_Action
{
    public function errorAction()
    {
        $errors = $this->_getRequest('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;
        }
    }
}
?>
7.10.5.1.2. Plugin Usage Examples

Voorbeeld 7.11. Standard usage

<?php
require_once 'Zend/Controller/Front.php';
require_once 'Zend/Controller/Plugin/ErrorHandler.php';

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

Voorbeeld 7.12. Setting a different error handler

<?php
require_once 'Zend/Controller/Front.php';
require_once 'Zend/Controller/Plugin/ErrorHandler.php';

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

Voorbeeld 7.13. Using accessors

<?php
require_once 'Zend/Controller/Front.php';
require_once 'Zend/Controller/Plugin/ErrorHandler.php';

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

$front = Zend_Controller_Front::getInstance();
$front->registerPlugin($plugin);
?>
7.10.5.1.3. Error Controller Example

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

<?php
class ErrorController extends Zend_Controller_Action
{
    public function errorAction()
    {
        $errors = $this->_getRequest('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 =<<<EOH
<h1>Error!</h1>
<p>The page you requested was not found.</p>
EOH;
                break;
            default:
                // application error
                $content =<<<EOH
<h1>Error!</h1>
<p>An unexpected error occurred with your request. Please try again later.</p>
EOH;
                break;
        }
        $this->initView();
        $this->view->content = $content;
        $this->render();
    }
}
?>