Documentation

Plugins - Zend_Controller

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:

  1. class MyPlugin extends Zend_Controller_Plugin_Abstract
  2. {
  3.     // ...
  4. }

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:

  1. class MyPlugin extends Zend_Controller_Plugin_Abstract
  2. {
  3.     public function routeStartup(Zend_Controller_Request_Abstract $request)
  4.     {
  5.         $this->getResponse()
  6.              ->appendBody("<p>routeStartup() called</p>\n");
  7.     }
  8.  
  9.     public function routeShutdown(Zend_Controller_Request_Abstract $request)
  10.     {
  11.         $this->getResponse()
  12.              ->appendBody("<p>routeShutdown() called</p>\n");
  13.     }
  14.  
  15.     public function dispatchLoopStartup(
  16.         Zend_Controller_Request_Abstract $request)
  17.     {
  18.         $this->getResponse()
  19.              ->appendBody("<p>dispatchLoopStartup() called</p>\n");
  20.     }
  21.  
  22.     public function preDispatch(Zend_Controller_Request_Abstract $request)
  23.     {
  24.         $this->getResponse()
  25.              ->appendBody("<p>preDispatch() called</p>\n");
  26.     }
  27.  
  28.     public function postDispatch(Zend_Controller_Request_Abstract $request)
  29.     {
  30.         $this->getResponse()
  31.              ->appendBody("<p>postDispatch() called</p>\n");
  32.     }
  33.  
  34.     public function dispatchLoopShutdown()
  35.     {
  36.         $this->getResponse()
  37.              ->appendBody("<p>dispatchLoopShutdown() called</p>\n");
  38.     }
  39. }
  40.  
  41. $front = Zend_Controller_Front::getInstance();
  42. $front->setControllerDirectory('/path/to/controllers')
  43.       ->setRouter(new Zend_Controller_Router_Rewrite())
  44.       ->registerPlugin(new MyPlugin());
  45. $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:

  1. <p>routeStartup() called</p>
  2. <p>routeShutdown() called</p>
  3. <p>dispatchLoopStartup() called</p>
  4. <p>preDispatch() called</p>
  5. <p>postDispatch() called</p>
  6. <p>dispatchLoopShutdown() called</p>

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 when no route matched

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

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

  1. class ErrorController extends Zend_Controller_Action
  2. {
  3.     public function errorAction()
  4.     {
  5.         $errors = $this->_getParam('error_handler');
  6.     }
  7. }

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_ROUTE, indicating no route matched.

  • 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 three types, and, if so, indicate a 404 page:

  1. class ErrorController extends Zend_Controller_Action
  2. {
  3.     public function errorAction()
  4.     {
  5.         $errors = $this->_getParam('error_handler');
  6.  
  7.         switch ($errors->type) {
  8.             case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ROUTE:
  9.             case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER:
  10.             case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION:
  11.                 // 404 error -- controller or action not found
  12.                 $this->getResponse()
  13.                      ->setRawHeader('HTTP/1.1 404 Not Found');
  14.  
  15.                 // ... get some output to display...
  16.                 break;
  17.             default:
  18.                 // application error; display error page, but don't
  19.                 // change status code
  20.                 break;
  21.         }
  22.     }
  23. }

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

  1. public function errorAction()
  2. {
  3.         $errors = $this->_getParam('error_handler');
  4.  
  5.         switch ($errors->type) {
  6.             case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ROUTE:
  7.             case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER:
  8.             case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION:
  9.                 // 404 error -- controller or action not found
  10.                 $this->getResponse()
  11.                      ->setRawHeader('HTTP/1.1 404 Not Found');
  12.  
  13.                 // ... get some output to display...
  14.                 break;
  15.             default:
  16.                 // application error; display error page, but don't change
  17.                 // status code
  18.  
  19.                 // ...
  20.  
  21.                 // Log the exception:
  22.                 $exception = $errors->exception;
  23.                 $log = new Zend_Log(
  24.                     new Zend_Log_Writer_Stream(
  25.                         '/tmp/applicationException.log'
  26.                     )
  27.                 );
  28.                 $log->debug($exception->getMessage() . "\n" .
  29.                             $exception->getTraceAsString());
  30.                 break;
  31.         }
  32. }

Handling Previously Rendered Output

If you dispatch multiple actions in a request, or if your action makes multiple calls to render(), it's 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:

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

Plugin Usage Examples

Example #1 Standard Usage

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

Example #2 Setting a Different Error Handler

  1. $front = Zend_Controller_Front::getInstance();
  2. $front->registerPlugin(new Zend_Controller_Plugin_ErrorHandler(array(
  3.     'module'     => 'mystuff',
  4.     'controller' => 'static',
  5.     'action'     => 'error'
  6. )));

Example #3 Using Accessors

  1. $plugin = new Zend_Controller_Plugin_ErrorHandler();
  2. $plugin->setErrorHandlerModule('mystuff')
  3.        ->setErrorHandlerController('static')
  4.        ->setErrorHandlerAction('error');
  5.  
  6. $front = Zend_Controller_Front::getInstance();
  7. $front->registerPlugin($plugin);

Error Controller Example

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

  1. class ErrorController extends Zend_Controller_Action
  2. {
  3.     public function errorAction()
  4.     {
  5.         $errors = $this->_getParam('error_handler');
  6.  
  7.         switch ($errors->type) {
  8.             case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ROUTE:
  9.             case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER:
  10.             case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION:
  11.                 // 404 error -- controller or action not found
  12.                 $this->getResponse()->setRawHeader('HTTP/1.1 404 Not Found');
  13.  
  14.                 $content =<<<EOH
  15. <h1>Error!</h1>
  16. <p>The page you requested was not found.</p>
  17. EOH;
  18.                 break;
  19.             default:
  20.                 // application error
  21.                 $content =<<<EOH
  22. <h1>Error!</h1>
  23. <p>An unexpected error occurred. Please try again later.</p>
  24. EOH;
  25.                 break;
  26.         }
  27.  
  28.         // Clear previous content
  29.         $this->getResponse()->clearBody();
  30.  
  31.         $this->view->content = $content;
  32.     }
  33. }

Zend_Controller_Plugin_PutHandler

Zend_Controller_Plugin_PutHandler provides a drop-in plugin for marshalling PUT request bodies into request parameters, just like POST request bodies. It will inspect the request and, if PUT, will use parse_str to parse the raw PUT body into an array of params which is then set on the request. E.g.,

  1. PUT /notes/5.xml HTTP/1.1
  2.  
  3. title=Hello&body=World

To receive the 'title' and 'body' params as regular request params, register the plugin:

  1. $front = Zend_Controller_Front::getInstance();
  2. $front->registerPlugin(new Zend_Controller_Plugin_PutHandler());

Then you can access the PUT body params by name from the request inside your controller:

  1. ...
  2. public function putAction()
  3. {
  4.     $title = $this->getRequest()->getParam('title'); // $title = "Hello"
  5.     $body = $this->getRequest()->getParam('body'); // $body = "World"
  6. }
  7. ...

Copyright

© 2006-2021 by Zend by Perforce. Made with by awesome contributors.

This website is built using zend-expressive and it runs on PHP 7.

Contacts