Programmer's Reference Guide
Action Helpers allow developers to inject runtime and/or on-demand functionality into any Action Controllers that extend Zend_Controller_Action. Action Helpers aim to minimize the necessity to extend the abstract Action Controller in order to inject common Action Controller functionality.
There are a number of ways to use Action Helpers. Action Helpers
employ the use of a brokerage system, similar to the types of
brokerage you see in Zend_View_Helper, and that
of Zend_Controller_Plugin.
Action Helpers (like Zend_View_Helper) may be
loaded and called on demand, or they may be instantiated at
request time (bootstrap) or action controller creation time
(init()). To understand this more fully, please see the usage
section below.
A helper can be initialized in several different ways, based on your needs as well as the functionality of that helper.
The helper broker is stored as the $_helper member of
Zend_Controller_Action; use the broker to retrieve or
call on helpers. Some methods for doing so include:
-
Explicitly using
getHelper(). Simply pass it a name, and a helper object is returned:<?php
$flashMessenger = $this->_helper->getHelper('FlashMessenger');
$flashMessenger->addMessage('We did something in the last request'); -
Use the helper broker's
__get()functionality and retrieve the helper as if it were a member property of the broker:<?php
$flashMessenger = $this->_helper->FlashMessenger;
$flashMessenger->addMessage('We did something in the last request'); -
Finally, most action helpers implement the method
direct()which will call a specific, default method in the helper. In the example of theFlashMessenger, it callsaddMessage():<?php
$this->_helper->FlashMessenger('We did something in the last request');
![]() |
Note |
|---|---|
All of the above examples are functionally equivalent. |
You may also instantiate helpers explicitly. You may wish to do this if using the helper outside of an action controller, or if you wish to pass a helper to the helper broker for use by any action. Instantiation is as per any other PHP class.
Zend_Controller_Action_HelperBroker handles the details
of registering helper objects and helper paths, as well as
retrieving helpers on-demand.
To register a helper with the broker, use addHelper:
<?php
Zend_Controller_Action_HelperBroker::addHelper($helper);
Of course, instantiating and passing helpers to the broker is a bit
time and resource intensive, so two methods exists to automate
things slightly: addPrefix() and
addPath().
-
addPrefix()takes a class prefix and uses it to determine a path where helper classes have been defined. It assumes the prefix follows Zend Framework class naming conventions.<?php
// Add helpers prefixed with My_Action_Helpers in My/Action/Helpers/
Zend_Controller_Action_HelperBroker::addPrefix('My_Action_Helpers'); -
addPath()takes a directory as its first argument and a class prefix as the second argument (defaulting to 'Zend_Controller_Action_Helper'). This allows you to map your own class prefixes to specific directories.<?php
// Add helpers prefixed with Helper in Plugins/Helpers/
Zend_Controller_Action_HelperBroker::addPath('./Plugins/Helpers', 'Helper');
Since these methods are static, they may be called at any point in the controller chain in order to dynamically add helpers as needed.
To determine if a helper exists in the helper broker, use
hasHelper($name), where $name is the short
name of the helper (minus the prefix):
<?php
// Check if 'redirector' helper is registered with the broker:
if (Zend_Controller_Action_HelperBroker::hasHelper('redirector')) {
echo 'Redirector helper registered';
}
There are also two static methods for retrieving helpers from the helper
broker: getExistingHelper() and
getStaticHelper(). getExistingHelper()
will retrieve a helper only if it has previously been invoked by or
explicitly registered with the helper broker; it will throw an
exception if not. getStaticHelper() does the same as
getExistingHelper(), but will attempt to instantiate
the helper if has not yet been registered with the helper stack.
getStaticHelper() is a good choice for retrieving
helpers which you wish to configure.
Both methods take a single argument, $name, which is
the short name of the helper (minus the prefix).
<?php
// Check if 'redirector' helper is registered with the broker, and fetch:
if (Zend_Controller_Action_HelperBroker::hasHelper('redirector')) {
$redirector = Zend_Controller_Action_HelperBroker::getExistingHelper('redirector');
}
// Or, simply retrieve it, not worrying about whether or not it was previously
// registered:
$redirector = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector');
}
Finally, to delete a registered helper from the broker, use
removeHelper($name), where $name is the
short name of the helper (minus the prefix):
<?php
// Conditionally remove the 'redirector' helper from the broker:
if (Zend_Controller_Action_HelperBroker::hasHelper('redirector')) {
Zend_Controller_Action_HelperBroker::removeHelper('redirector')
}
Zend Framework includes several action helpers by default:
AutoComplete for automating responses for AJAX
autocompletion; ContextSwitch and
AjaxContext for serving alternate response formats for
your actions; a FlashMessenger for handling session
flash messages; Json for encoding and sending JSON
responses; a Redirector, to provide different
implementations for redirecting to internal and external pages from
your application; and a ViewRenderer to automate the
process of setting up the view object in your controllers and
rendering views.
The ActionStack helper allows you to push requests to the
ActionStack
front controller plugin, effectively helping you create a queue of
actions to execute during the request. The helper allows you to add
actions either by specifying new request objects or
action/controller/module sets.
![]() |
Invoking ActionStack helper initializes ActionStack Plugin |
|---|---|
Invoking the |
Example 7.2. Adding a task using action, controller and module names
Often, it's simplest to simply specify the action, controller, and
module (and optional request parameters), much as you would when
calling Zend_Controller_Action::_forward():
<?php
class FooController extends Zend_Controller_Action
{
public function barAction()
{
// Add two actions to the stack
// Add call to /foo/baz/bar/baz
// (FooController::bazAction() with request var bar == baz)
$this->_helper->actionStack('baz', 'foo', 'default', array('bar' => 'baz'));
// Add call to /bar/bat
// (BarController::batAction())
$this->_helper->actionStack('bat', 'bar');
}
}
?>
Example 7.3. Adding a task using a request object
Sometimes the OOP nature of a request object makes most sense; you
can pass such an object to the ActionStack helper as
well.
<?php
class FooController extends Zend_Controller_Action
{
public function barAction()
{
// Add two actions to the stack
// Add call to /foo/baz/bar/baz
// (FooController::bazAction() with request var bar == baz)
$request = clone $this->getRequest();
$request->setActionName('baz') // don't set controller or
->setParams(array('bar' => 'baz')); // module; use current values
$this->_helper->actionStack($request);
// Add call to /bar/bat
// (BarController::batAction())
$request = clone $this->getRequest();
$request->setActionName('bat') // don't set module; use current
->setControllerName('bar'); // value
$this->_helper->actionStack($request);
}
}
?>
Many AJAX javascript libraries offer functionality for providing
autocompletion whereby a selectlist of potentially matching results is
displayed as the user types. The AutoComplete helper aims
to simplify returning acceptable responses to such methods.
Since not all JS libraries implement autocompletion in the same way, the
AutoComplete helper provides some abstract base
functionality necessary to many libraries, and concrete implementations
for individual libraries. Return types are generally either JSON arrays
of strings, JSON arrays of arrays (with each member array being an
associative array of metadata used to create the selectlist), or HTML.
Basic usage for each implementation is the same:
<?php
class FooController extends Zend_Controller_Action
{
public function barAction()
{
// Perform some logic...
// Encode and send response;
$this->_helper->autoCompleteDojo($data);
// Or explicitly:
$response = $this->_helper->autoCompleteDojo->sendAutoCompletion($data);
// Or simply prepare autocompletion response:
$response = $this->_helper->autoCompleteDojo->prepareAutoCompletion($data);
}
}
?>
By default, autocompletion does the following:
Disables layouts and ViewRenderer.
Sets appropriate response headers.
Sets response body with encoded/formatted autocompletion data.
Sends response.
Available methods of the helper include:
disableLayouts()can be used to disable layouts and the ViewRenderer. Typically, this is called withinprepareAutoCompletion().encodeJson($data, $keepLayouts = false)will encode data to JSON, optionally enabling or disabling layouts. Typically, this is called withinprepareAutoCompletion().prepareAutoCompletion($data, $keepLayouts = false)is used to prepare data in the response format necessary for the concrete implementation, optionally enabling or disabling layouts. The return value will vary based on the implementation.sendAutoCompletion($data, $keepLayouts = false)is used to send data in the response format necessary for the concrete implementation. It callsprepareAutoCompletion(), and then sends the response.direct($data, $sendNow = true, $keepLayouts = false)is used when calling the helper as a method of the helper broker. The$sendNowflag is used to determine whether to callsendAutoCompletion()orprepareAutoCompletion(), respectively.
Currently, AutoComplete supports the Dojo and Scriptaculous
AJAX libraries.
Dojo does not have an AutoCompletion widget per se, but has two widgets that can perform AutoCompletion: ComboBox and FilteringSelect. In both cases, they require a data store that implements the QueryReadStore; for more information on these topics, see the dojo.data documentation.
In Zend Framework, you can pass a simple indexed array to the AutoCompleteDojo helper, and it will return a JSON response suitable for use with such a store:
<?php
// within a controller action:
$this->_helper->autoCompleteDojo($data);
Example 7.4. AutoCompletion with Dojo Using Zend MVC
AutoCompletion with Dojo via the Zend MVC requires several things: generating a form object for the ComboBox on which you want AutoCompletion, a controller action for serving the AutoCompletion results, creating a custom QueryReadStore to connect to the AutoCompletion action, and generation of the javascript to use to initialize AutoCompletion on the server side.
First, let's look at the javascript necessary. Dojo offers a complete framework for creating OOP javascript, much as Zend Framework does for PHP. Part of that is the ability to create pseudo-namespaces using the directory hierarchy. We'll create a 'custom' directory at the same level as the Dojo directory that's part of the Dojo distribution. Inside that directory, we'll create a javascript file, TestNameReadStore.js, with the following contents:
dojo.provide("custom.TestNameReadStore");
dojo.declare("custom.TestNameReadStore", dojox.data.QueryReadStore, {
fetch:function (request) {
request.serverQuery = { test:request.query.name };
return this.inherited("fetch", arguments);
}
});
This class is simply an extension of Dojo's own QueryReadStore, which is itself an abstract class. We simply define a method by which to request, and assigning it to the 'test' element.
Next, let's create the form element for which we want AutoCompletion:
<?php
class TestController extends Zend_Controller_Action
{
protected $_form;
public function getForm()
{
if (null === $this->_form) {
require_once 'Zend/Form.php';
$this->_form = new Zend_Form();
$this->_form->setMethod('get')
->setAction($this->getRequest()->getBaseUrl() . '/test/process')
->addElements(array(
'test' => array('type' => 'text', 'options' => array(
'filters' => array('StringTrim'),
'dojoType' => array('dijit.form.ComboBox'),
'store' => 'testStore',
'autoComplete' => 'false',
'hasDownArrow' => 'true',
'label' => 'Your input:',
)),
'go' => array('type' => 'submit', 'options' => array('label' => 'Go!'))
));
}
return $this->_form;
}
}
Here, we simply create a form with 'test' and 'go' methods. The 'test' method adds several special, Dojo-specific attributes: dojoType, store, autoComplete, and hasDownArrow. The dojoType is used to indicate that we are creating a ComboBox, and we will link it to a data store (key 'store') of 'testStore' -- more on that later. Specifying 'autoComplete' as false tells Dojo not to automatically select the first match, but instead show a list of matches. Finally, 'hasDownArrow' creates a down arrow similar to a select box so we can show and hide the matches.
Let's add a method to display the form, as well as an end point for processing AutoCompletion:
<?php
class TestController extends Zend_Controller_Action
{
// ...
/**
* Landing page
*/
public function indexAction()
{
$this->view->form = $this->getForm();
}
public function autocompleteAction()
{
if ('ajax' != $this->_getParam('format', false)) {
return $this->_helper->redirector('index');
}
if ($this->getRequest()->isPost()) {
return $this->_helper->redirector('index');
}
$match = trim($this->getRequest()->getQuery('test', ''));
$matches = array();
foreach ($this->getData() as $datum) {
if (0 === strpos($datum, $match)) {
$matches[] = $datum;
}
}
$this->_helper->autoCompleteDojo($matches);
}
}
In our autocompleteAction() we do a number of
things. First, we look to make sure we have a post request, and
that there is a 'format' parameter set to the value 'ajax';
these are simply to help reduce spurious queries to the action.
Next, we check for a 'test' parameter, and compare it against
our data. (I purposely leave out the implementation of
getData() here -- it could be any sort of data
source.) Finally, we send our matches to our AutoCompletion
helper.
Now that we have all the pieces on the backend, let's look at what we need to deliver in our view script for the landing page. First, we need to setup our data store, then render our form, and finally ensure that the appropriate Dojo libraries -- including our custom data store -- get loaded. Let's look at the view script, which comments the steps:
<? // setup our data store: ?>
<div dojoType="custom.TestNameReadStore" jsId="testStore"
url="<?= $this->baseUrl() ?>/unit-test/autocomplete/format/ajax" requestMethod="get"></div>
<? // render our form: ?>
<?= $this->form ?>
<? // setup Dojo-related CSS to load in HTML head: ?>
<? $this->headStyle()->captureStart() ?>
@import "<?= $this->baseUrl() ?>/javascript/dijit/themes/tundra/tundra.css";
@import "<?= $this->baseUrl() ?>/javascript/dojo/resources/dojo.css";
<? $this->headStyle()->captureEnd() ?>
<? // setup javascript to load in HTML head, including all required Dojo
// libraries: ?>
<? $this->headScript()
->setAllowArbitraryAttributes(true)
->appendFile($this->baseUrl() . '/javascript/dojo/dojo.js',
'text/javascript',
array('djConfig' => 'parseOnLoad: true'))
->captureStart() ?>
djConfig.usePlainJson=true;
dojo.registerModulePath("custom","../custom");
dojo.require("dojo.parser");
dojo.require("dojox.data.QueryReadStore");
dojo.require("dijit.form.ComboBox");
dojo.require("custom.TestNameReadStore");
<? $this->headScript()->captureEnd() ?>
Note the calls to view helpers such as headStyle and headScript; these are placeholders, which we can then render in the HTML head section of our layout view script.
We now have all the pieces to get Dojo AutoCompletion working.
Scriptaculous expects an HTML response in a specific format.
The helper to use with this library is 'AutoCompleteScriptaculous'. Simply provide it an array of data, and the helper will create an HTML response compatible with Ajax.Autocompleter.
The ContextSwitch action helper is intended for
facilitating returning different response formats on request.
The AjaxContext helper is a specialized version of
ContextSwitch that facilitates returning responses
to XmlHttpRequests.
To enable either one, you must provide hinting in your controller as to what actions can respond to which contexts. If an incoming request indicates a valid context for the given action, the helper will then:
Disable layouts, if enabled.
Set an alternate view suffix, effectively requiring a separate view script for the context.
Send appropriate response headers for the context desired.
Optionally, call specified callbacks to setup the context and/or perform post-processing.
As an example, let's consider the following controller:
<?php
class NewsController extends Zend_Controller_Action
{
/**
* Landing page; forwards to listAction()
*/
public function indexAction()
{
$this->_forward('list');
}
/**
* List news items
*/
public function listAction()
{
}
/**
* View a news item
*/
public function viewAction()
{
}
}
?>
Let's say that we want the listAction() to also be
available in an XML format. Instead of creating a different action, we
can hint that it can return an XML response:
<?php
class NewsController extends Zend_Controller_Action
{
public function init()
{
$contextSwitch = $this->_helper->getHelper('contextSwitch');
$contextSwitch->addActionContext('list', 'xml')
->initContext();
}
// ...
}
?>
What this will do is:
Set the 'Content-Type' response header to 'text/xml'.
Change the view suffix to 'xml.phtml' (or, if you use an alternate view suffix, 'xml.[your suffix]').
Now, you'll need to create a new view script, 'news/list.xml.phtml', which will create and render the XML.
To determine if a request should initiate a context switch, the helper checks for a token in the request object. By default, it looks for the 'format' parameter, though this may be configured. This means that, in most cases, to trigger a context switch, you can add a 'format' parameter to your request:
Via URL parameter:
/news/list/format/xml(recall, the default routing schema allows for arbitrary key/value pairs following the action)Via GET parameter:
/news/list?format=xml
ContextSwitch allows you to specify arbitrary contexts,
including what suffix change will occur (if any), any response headers
that should be sent, and arbitrary callbacks for initialization and post
processing.
By default, two contexts are available to the
ContextSwitch helper: json and xml.
-
JSON. The JSON context sets the 'Content-Type' response header to 'application/json', and the view script suffix to 'json.phtml'.
By default, however, no view script is required. It will simply serialize all view variables, and emit the JSON response immediately.
This behaviour can be disabled by turning off auto-JSON serialization:
<?php
$this->_helper->contextSwitch()->setAutoJsonSerialization(false);
?> XML. The XML context sets the 'Content-Type' response header to 'text/xml', and the view script suffix to 'xml.phtml'. You will need to create a new view script for the context.
Sometimes, the default contexts are not enough. For instance, you
may wish to return YAML, or serialized PHP, an RSS or ATOM feed,
etc. ContextSwitch allows you to do so.
The easiest way to add a new context is via the
addContext() method. This method takes two arguments,
the name of the context, and an array specification. The
specification should include one or more of the following:
suffix: the suffix to prepend to the default view suffix as registered in the ViewRenderer.
headers: an array of header/value pairs you wish sent as part of the response.
-
callbacks: an array containing one or more of the keys 'init' or 'post', pointing to valid PHP callbacks that can be used for context initialization and post processing.
Initialization callbacks occur when the context is detected by
ContextSwitch. You can use it to perform arbitrary logic that should occur. As an example, the JSON context uses a callback to disable the ViewRenderer when auto-JSON serialization is on.Post processing occurs during the action's
postDispatch()routine, and can be used to perform arbitrary logic. As an example, the JSON context uses a callback to determine if auto-JSON serialization is on; if so, it serializes the view variables to JSON and sends the response, but if not, it re-enables the ViewRenderer.
There are a variety of methods for interacting with contexts:
addContext($context, array $spec): add a new context. Throws an exception if the context already exists.setContext($context, array $spec): add a new context or overwrite an existing context. Uses the same specification asaddContext().addContexts(array $contexts): add many contexts at once. The$contextsarray should be an array of context/specification pairs. If any of the contexts already exists, it will throw an exception.setContexts(array $contexts): add new contexts and overwrite existing ones. Uses the same specification asaddContexts().hasContext($context): returns true if the context exists, false otherwise.getContext($context): retrieve a single context by name. Returns an array following the specification used inaddContext().getContexts(): retrieve all contexts. Returns an array of context/specification pairs.removeContext($context): remove a single context by name. Returns true if successful, false if the context was not found.clearContexts(): remove all contexts.
There are two mechanisms for setting available contexts. You can
either manually create arrays in your controller, or use several
methods in ContextSwitch to assemble them.
The principle method for adding action/context relations is
addActionContext(). It expects two arguments, the
action to which the context is being added, and either the name of a
context or an array of contexts. As an example, consider the
following controller class:
<?php
class FooController extends Zend_Controller_Action
{
public function listAction()
{
}
public function viewAction()
{
}
public function commentsAction()
{
}
public function updateAction()
{
}
}
?>
Let's say we wanted to add an XML context to the 'list' action, and
XML and JSON contexts to the 'comments' action. We could do so in
the init() method:
<?php
class FooController extends Zend_Controller_Action
{
public function init()
{
$this->_helper->contextSwitch()
->addActionContext('list', 'xml')
->addActionContext('comments', array('xml', 'json'))
->initContext();
}
}
?>
Alternately, you could simply define the array property
$contexts:
<?php
class FooController extends Zend_Controller_Action
{
public $contexts = array(
'list' => array('xml'),
'comments' => array('xml', 'json')
);
public function init()
{
$this->_helper->contextSwitch()->initContext();
}
}
?>
The above is less overhead, but also prone to potential errors.
The following methods can be used to build the context mappings:
-
addActionContext($action, $context): marks one or more contexts as available to an action. If mappings already exists, simply appends to those mappings.$contextmay be a single context, or an array of contexts.A value of
truefor the context will mark all available contexts as available for the action.An empty value for $context will disable all contexts for the given action.
setActionContext($action, $context): marks one or more contexts as available to an action. If mappings already exists, it replaces them with those specified.$contextmay be a single context, or an array of contexts.addActionContexts(array $contexts): add several action/context pairings at once.$contextsshould be an associative array of action/context pairs. It proxies toaddActionContext(), meaning that if pairings already exist, it appends to them.setActionContexts(array $contexts): acts likeaddActionContexts(), but overwrites existing action/context pairs.hasActionContext($action, $context): determine if a particular action has a given context.getActionContexts($action = null): returns either all contexts for a given action, or all action/context pairs.removeActionContext($action, $context): remove one or more contexts from a given action.$contextmay be a single context or an array of contexts.clearActionContexts($action = null): remove all contexts from a given action, or from all actions with contexts.
To initialize context switching, you need to call
initContext() in your action controller:
<?php
class NewsController extends Zend_Controller_Action
{
public function init()
{
$this->_helper->contextSwitch()->initContext();
}
}
?>
In some cases, you may want to force the context used; for instance,
you may only want to allow the XML context if context switching is
activated. You can do so by passing the context to
initContext():
<?php
$contextSwitch->initContext('xml');
?>
A variety of methods can be used to alter the behaviour of the
ContextSwitch helper. These include:
-
setAutoJsonSerialization($flag): By default, JSON contexts will serialize any view variables to JSON notation and return this as a response. If you wish to create your own response, you should turn this off; this needs to be done prior to the call toinitContext().<?php
$contextSwitch->setAutoJsonSerialization(false);
$contextSwitch->initContext();
?>You can retrieve the value of the flag with
getAutoJsonSerialization(). -
setSuffix($context, $suffix, $prependViewRendererSuffix): With this method, you can specify a different suffix to use for a given context. The third argument is used to indicate whether or not to prepend the current ViewRenderer suffix with the new suffix; this flag is enabled by default.Passing an empty value to the suffix will cause only the ViewRenderer suffix to be used.
-
addHeader($context, $header, $content): Add a response header for a given context.$headeris the header name, and$contentis the value to pass for that header.Each context can have multiple headers;
addHeader()adds additional headers to the context's header stack.If the
$headerspecified already exists for the context, an exception will be thrown. setHeader($context, $header, $content):setHeader()acts just likeaddHeader(), except it allows you to overwrite existing context headers.addHeaders($context, array $headers): Add multiple headers at once to a given context. Proxies toaddHeader(), so if the header already exists, an exception will be thrown.$headersis an array of header/context pairs.setHeaders($context, array $headers.): likeaddHeaders(), except it proxies tosetHeader(), allowing you to overwrite existing headers.getHeader($context, $header): retrieve the value of a header for a given context. Returns null if not found.removeHeader($context, $header): remove a single header for a given context.clearHeaders($context, $header): remove all headers for a given context.setCallback($context, $trigger, $callback): set a callback at a given trigger for a given context. Triggers may be either 'init' or 'post' (indicating callback will be called at either context initialization or postDispatch).$callbackshould be a valid PHP callback.setCallbacks($context, array $callbacks): set multiple callbacks for a given context.$callbacksshould be trigger/callback pairs. In actuality, the most callbacks that can be registered are two, one for initialization and one for post processing.getCallback($context, $trigger): retrieve a callback for a given trigger in a given context.getCallbacks($context): retrieve all callbacks for a given context. Returns an array of trigger/callback pairs.removeCallback($context, $trigger): remove a callback for a given trigger and context.clearCallbacks($context): remove all callbacks for a given context.-
setContextParam($name): set the request parameter to check when determining if a context switch has been requested. The value defaults to 'format', but this accessor can be used to set an alternate value.getContextParam()can be used to retrieve the current value. -
setAutoDisableLayout($flag): By default, layouts are disabled when a context switch occurs; this is because typically layouts will only be used for returning normal responses, and have no meaning in alternate contexts. However, if you wish to use layouts (perhaps you may have a layout for the new context), you can change this behaviour by passing a false value tosetAutoDisableLayout(). You should do this before callinginitContext().To get the value of this flag, use the accessor
getAutoDisableLayout(). getCurrentContext()can be used to determine what context was detected, if any. This returns null if no context switch occurred, or if called beforeinitContext()has been invoked.
The AjaxContext helper extends
ContextSwitch, so all of the functionality listed for
ContextSwitch is available to it. There are a few key
differences, however.
First, it uses a different action controller property for
determining contexts, $ajaxable. This is so you can
have different contexts used for AJAX versus normal HTTP requests.
The various *ActionContext*() methods of
AjaxContext will write to this property.
Second, it will only trigger if an XmlHttpRequest has occurred, as
determined by the request object's isXmlHttpRequest()
method. Thus, if the context parameter ('format') is passed in the
request, but the request was not made as an XmlHttpRequest, no
context switch will trigger.
Third, AjaxContext adds an additional context, HTML. In
this context, it sets the suffix to 'ajax.phtml' in order to
differentiate the context from a normal request. No additional
headers are returned.
Example 7.5. Allowing Actions to Respond To Ajax Requests
In this following example, we're allowing requests to the actions 'view', 'form', and 'process' to respond to AJAX requests. In the first two cases, 'view' and 'form', we'll return HTML snippets with which to update the page; in the latter, we'll return JSON.
<?php
class CommentController extends Zend_Controller_Action
{
public function init()
{
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('view', 'html')
->addActionContext('form', 'html')
->addActionContext('process', 'json')
->initContext();
}
public function viewAction()
{
// Pull a single comment to view.
// When AjaxContext detected, uses the comment/view.ajax.phtml
// view script.
}
public function formAction()
{
// Render the "add new comment" form.
// When AjaxContext detected, uses the comment/form.ajax.phtml
// view script.
}
public function processAction()
{
// Process a new comment
// Return the results as JSON; simply assign the results as view
// variables, and JSON will be returned.
}
}
?>
On the client end, your AJAX library will simply request the endpoints '/comment/view', '/comment/form', and '/comment/process', and pass the 'format' parameter: '/comment/view/format/html', '/comment/form/format/html', '/comment/process/format/json'. (Or you can pass the parameter via query string: e.g., "?format=json".)
Assuming your library passes the 'X-Requested-With: XmlHttpRequest' header, these actions will then return the appropriate response format.
The FlashMessenger helper allows you to pass messages
that the user may need to see on the next request. To accomplish
this, FlashMessenger uses
Zend_Session_Namespace to store messages for future or
next request retrieval. It is generally a good idea that if you
plan on using Zend_Session or
Zend_Session_Namespace, that you initialize with
Zend_Session::start() in your bootstrap file. (See the
Zend_Session
documentation for more details on its usage.)
The usage example below shows the use of the flash messenger at its
most basic. When the action /some/my is called, it adds
the flash message "Record Saved!" A subsequent request to the action
/some/my-next-request will retrieve it (and thus delete
it as well).
<?php
class SomeController extends Zend_Controller_Action
{
/**
* FlashMessenger
*
* @var Zend_Controller_Action_Helper_FlashMessenger
*/
protected $_flashMessenger = null;
public function init()
{
$this->_flashMessenger = $this->_helper->getHelper('FlashMessenger');
$this->initView();
}
public function myAction()
{
/**
* default method of getting Zend_Controller_Action_Helper_FlashMessenger
* instance on-demand
*/
$this->_flashMessenger->addMessage('Record Saved!');
}
public function myNextRequestAction()
{
$this->view->messages = $this->_flashMessenger->getMessages();
$this->render();
}
}
JSON responses are rapidly becoming the response of choice when dealing with AJAX requests that expect dataset responses; JSON can be immediately parsed on the client-side, leading to quick execution.
The JSON action helper does several things:
Disables layouts if currently enabled.
Disables the ViewRenderer if currently enabled.
Sets the 'Content-Type' response header to 'application/json'.
By default, immediately returns the response, without waiting for the action to finish execution.
Usage is simple: either call it as a method of the helper broker, or
call one of the methods encodeJson() or
sendJson():
<?php
class FooController extends Zend_Controller_Action
{
public function barAction()
{
// do some processing...
// Send the JSON response:
$this->_helper->json($data);
// or...
$this->_helper->json->sendJson($data);
// or retrieve the json:
$json = $this->_helper->json->encodeJson($data);
}
}
?>
![]() |
Keeping Layouts |
|---|---|
|
If you have a separate layout for JSON responses -- perhaps to wrap
the JSON response in some sort of context -- each method in the JSON
helper accepts a second, optional argument: a flag to enable or
disable layouts. Passing a boolean
|
The Redirector helper allows you to use a redirector
object to fulfill your application's needs for redirecting to a new
URL. It provides numerous benefits over the
_redirect() method, such as being able to preconfigure
sitewide behavior into the redirector object or using the built in
gotoSimple($action, $controller, $module, $params) interface
similar to that of Zend_Controller_Action::_forward().
The Redirector has a number of methods that can be used
to affect the behaviour at redirect:
setCode()can be used to set the HTTP response code to use during the redirect.setExit()can be used to force anexit()following a redirect. By default this is true.setGotoSimple()can be used to set a default URL to use if none is passed togotoSimple(). Uses the API ofZend_Controller_Action::_forward(): setGotoSimple($action, $controller = null, $module = null, array $params = array());setGotoRoute()can be used to set a URL based on a registered route. Pass in an array of key/value pairs and a route name, and it will assemble the URL according to the route type and definition.setGotoUrl()can be used to set a default URL to use if none is passed togotoUrl(). Accepts a single URL string.setPrependBase()can be used to prepend the request object's base URL to a URL specified withsetGotoUrl(),gotoUrl(), orgotoUrlAndExit().setUseAbsoluteUri()can be used to force theRedirectorto use absolute URIs when redirecting. When this option is set, it uses the value of$_SERVER['HTTP_HOST'],$_SERVER['SERVER_PORT'], and$_SERVER['HTTPS']to form a full URI to the URL specified by one of the redirect methods. This option is off by default, but may be enabled by default in later releases.
Additionally, there are a variety of methods in the redirector for performing the actual redirects:
gotoSimple()usessetGotoSimple()(_forward()-like API) to build a URL and perform a redirect.gotoRoute()usessetGotoRoute()(route-assembly) to build a URL and perform a redirect.gotoUrl()usessetGotoUrl()(URL string) to build a URL and perform a redirect.
Finally, you can determine the current redirect URL at any time
using getRedirectUrl().
Example 7.6. Setting Options
This example overrides several options, including setting the HTTP status code to use in the redirect ('303'), not defaulting to exit on redirect, and defining a default URL to use when redirecting.
<?php
class SomeController extends Zend_Controller_Action
{
/**
* Redirector - defined for code completion
*
* @var Zend_Controller_Action_Helper_Redirector
*/
protected $_redirector = null;
public function init()
{
$this->_redirector = $this->_helper->getHelper('Redirector');
// Set the default options for the redirector
// Since the object is registered in the helper broker, these become
// relevant for all actions from this point forward
$this->_redirector->setCode('303')
->setExit(false)
->setGotoSimple("this-action", "some-controller");
}
public function myAction()
{
/* do some stuff */
// Redirect to a previously registered URL, and force an exit to occur
// when done:
$this->_redirector->redirectAndExit();
return; // never reached
}
}
Example 7.7. Using Defaults
This example assumes that the defaults are used, which means
that any redirect will result in an immediate
exit().
<?php
// ALTERNATIVE EXAMPLE
class AlternativeController extends Zend_Controller_Action
{
/**
* Redirector - defined for code completion
*
* @var Zend_Controller_Action_Helper_Redirector
*/
protected $_redirector = null;
public function init()
{
$this->_redirector = $this->_helper->getHelper('Redirector');
}
public function myAction()
{
/* do some stuff */
$this->_redirector->gotoUrl('/my-controller/my-action/param1/test/param2/test2');
return; // never reached since default is to goto and exit
}
}
Example 7.8. Using goto()'s _forward() API
gotoSimple()'s API mimics that of
Zend_Controller_Action::_forward(). The primary
difference is that it builds a URL from the parameters passed,
and using the default :module/:controller/:action/*
format of the default router. It then redirects instead of
chaining the action.
<?php
class ForwardController extends Zend_Controller_Action
{
/**
* Redirector - defined for code completion
*
* @var Zend_Controller_Action_Helper_Redirector
*/
protected $_redirector = null;
public function init()
{
$this->_redirector = $this->_helper->getHelper('Redirector');
}
public function myAction()
{
/* do some stuff */
// Redirect to 'my-action' of 'my-controller' in the current module,
// using the params param1 => test and param2 => test2
$this->_redirector->gotoSimple('my-action', 'my-controller', null, array('param1' => 'test', 'param2' => 'test2'));
}
}
Example 7.9. Using route assembly with gotoRoute()
The following example uses the router's
assemble() method to create a URL based on an
associative array of parameters passed. It assumes the following
route has been registered:
<?php
$route = new Zend_Controller_Router_Route(
'blog/:year/:month/:day/:id'<
![[Note]](/images/note.gif)