Programmer's Reference Guide
| The Response Object |
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 beforeZend_Controller_Frontcalls on the router to evaluate the request against the registered routes. -
routeShutdown()is called after the router finishes routing the request. -
dispatchLoopStartup()is called beforeZend_Controller_Frontenters 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 (viaZend_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 (viaZend_Controller_Request_Abstract::setDispatched(false)), a new action may be specified for dispatching. -
dispatchLoopShutdown()is called afterZend_Controller_Frontexits its dispatch loop.
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.
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(Zend_Controller_Request_Abstract $request)
{
$this->getResponse()->appendBody("<p>routeStartup() called</p>\n");
}
public function routeShutdown(Zend_Controller_Request_Abstract $request)
{
$this->getResponse()->appendBody("<p>routeShutdown() called</p>\n");
}
public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request)
{
$this->getResponse()->appendBody("<p>dispatchLoopStartup() called</p>\n");
}
public function preDispatch(Zend_Controller_Request_Abstract $request)
{
$this->getResponse()->appendBody("<p>preDispatch() called</p>\n");
}
public function postDispatch(Zend_Controller_Request_Abstract $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>
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.
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'):
<?php
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:
<?php
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:
<?php
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:
<?php
$this->getResponse()->clearBody();
Plugin Usage Examples
Exemple #1 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());
Exemple #2 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'
)));
Exemple #3 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);
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->_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 =<<<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;
}
// Clear previous content
$this->getResponse()->clearBody();
$this->view->content = $content;
}
}
| The Response Object |
Select a Version
Languages Available
Components
Search the Manual
Navigation
- Guide de référence du programmeur
- Guide de référence du programmeur
- Zend_Controller
- Zend_Controller - Démarrage rapide
- Fondations de Zend_Controller
- Le contrôleur frontal (Front Controller)
- L'objet Requête
- The Standard Router: Zend_Controller_Router_Rewrite
- Le dispatcheur
- Action Controllers
- Action Helpers
- The Response Object
- Plugins
- Using a Conventional Modular Directory Structure
- MVC Exceptions
- Migrer depuis des versions précédentes
