Action Helpers

The Response Object

Usage

The response object is the logical counterpart to the request object. Its purpose is to collate content and/or headers so that they may be returned en masse. Additionally, the front controller will pass any caught exceptions to the response object, allowing the developer to gracefully handle exceptions. This functionality may be overridden by setting Zend_Controller_Front::throwExceptions(true):

  1.  

To send the response output, including headers, use sendResponse().

  1.  

Note: By default, the front controller calls sendResponse() when it has finished dispatching the request; typically you will never need to call it. However, if you wish to manipulate the response or use it in testing, you can override this behaviour by setting the returnResponse flag with Zend_Controller_Front::returnResponse(true):

  1. span style="color: #808080; font-style: italic;">// do some more processing, such as logging...
  2. // and then send the output:

Developers should make use of the response object in their action controllers. Instead of directly rendering output and sending headers, push them to the response object:

  1. // Within an action controller action:
  2. // Set a header
  3. 'Content-Type', 'text/html'

By doing this, all headers get sent at once, just prior to displaying the content.

Note: If using the action controller view integration, you do not need to set the rendered view script content in the response object, as Zend_Controller_Action::render() does this by default.

Should an exception occur in an application, check the response object's isException() flag, and retrieve the exception using getException(). Additionally, one may create custom response objects that redirect to error pages, log exception messages, do pretty formatting of exception messages (for development environments), etc.

You may retrieve the response object following the front controller dispatch(), or request the front controller to return the response object instead of rendering output.

  1. // retrieve post-dispatch:
  2. // log, mail, etc...
  3. }
  4.  
  5. // Or, have the front controller dispatch() process return it
  6. // do some processing...
  7.  
  8. // finally, echo the response

By default, exception messages are not displayed. This behaviour may be overridden by calling renderExceptions(), or enabling the front controller to throwExceptions(), as shown above:

  1. span style="color: #808080; font-style: italic;">// or:
  2. // or:

Manipulating Headers

As stated previously, one aspect of the response object's duties is to collect and emit HTTP response headers. A variety of methods exist for this:

  • canSendHeaders() is used to determine if headers have already been sent. It takes an optional flag indicating whether or not to throw an exception if headers have already been sent. This can be overridden by setting the property headersSentThrowsException to FALSE.

  • setHeader($name, $value, $replace = false) is used to set an individual header. By default, it does not replace existing headers of the same name in the object; however, setting $replace to TRUE will force it to do so.

    Before setting the header, it checks with canSendHeaders() to see if this operation is allowed at this point, and requests that an exception be thrown.

  • setRedirect($url, $code = 302) sets an HTTP Location header for a redirect. If an HTTP status code has been provided, it will use that status code.

    Internally, it calls setHeader() with the $replace flag on to ensure only one such header is ever sent.

  • getHeaders() returns an array of all headers. Each array element is an array with the keys 'name' and 'value'.

  • clearHeaders() clears all registered headers.

  • setRawHeader() can be used to set headers that are not key and value pairs, such as an HTTP status header.

  • getRawHeaders() returns any registered raw headers.

  • clearRawHeaders() clears any registered raw headers.

  • clearAllHeaders() clears both regular key and value headers as well as raw headers.

In addition to the above methods, there are accessors for setting and retrieving the HTTP response code for the current request, setHttpResponseCode() and getHttpResponseCode().

Setting Cookie Headers

You can inject HTTP Set-Cookie headers into the response object of an action controller by using the provided header class Zend_Http_Header_SetCookie

Constructor Arguments

The following table lists all constructor arguments of Zend_Http_Header_SetCookie in the order they are accepted. All arguments are optional, but name and value must be supplied via their setters if not passed in via the constructor or the resulting Set-Cookie header be invalid.

  • $name: The name of the cookie

  • $value: The value of the cookie

  • $expires: The time the cookie expires

  • $path: The path on the server in which the cookie will be available

  • $domain: The domain to restrict cookie to

  • $secure: boolean indicating whether cookie should be sent over an unencrypted connection (false) or via HTTPS only (true)

  • $httpOnly: boolean indicating whether cookie should be transmitted only via the HTTP protocol

  • $maxAge: The maximum age of the cookie in seconds

  • $version: The cookie specification version

Example #1 Populate Zend_Http_Header_SetCookie via constructor and add to response

  1. span style="color: #ff0000;">'foo', 'bar''/', 'example.com'

Example #2 Populate Zend_Http_Header_SetCookie via setters and add to response

  1. span style="color: #ff0000;">'foo')
  2.        ->setValue('bar''example.com')
  3.        ->setPath('/'

Named Segments

The response object has support for "named segments". This allows you to segregate body content into different segments and order those segments so output is returned in a specific order. Internally, body content is saved as an array, and the various accessor methods can be used to indicate placement and names within that array.

As an example, you could use a preDispatch() hook to add a header to the response object, then have the action controller add body content, and a postDispatch() hook add a footer:

  1. // Assume that this plugin class is registered with the front controller
  2. '../views/scripts''header''header.phtml''../views/scripts''footer''footer.phtml'));
  3.     }
  4. }
  5.  
  6. // a sample action controller

In the above example, a call to /my/foo will cause the final body content of the response object to have the following structure:

  1. span style="color: #ff0000;">'header'  => ..., // header content
  2.     'default' => ..., // body content from MyController::fooAction()
  3.     'footer'  => ...  // footer content
  4. );

When this is rendered, it will render in the order in which elements are arranged in the array.

A variety of methods can be used to manipulate the named segments:

  • setBody() allows you to pass a second value, $name, indicating a named segment. If you provide a segment name it will overwrite that specific named segment or create it if it does not exist (appending to the body array by default). If no named segment is passed to setBody(), it resets the entire body content array.

  • appendBody() also allows you to pass a second value, $name, indicating a named segment. If you provide a segment name it will append the supplied content to the existing content in the named segment, or create the segment if it does not exist (appending to the body array by default). If no named segment is passed to appendBody(), it will append the supplied content to the named segment 'default', creating it if it does not already exist.

  • prepend($name, $content) will create a segment named $name and place it at the beginning of the array. If the segment exists already, it will be removed prior to the operation (i.e., overwritten and replaced).

  • append($name, $content) will create a segment named $name and place it at the end of the array. If the segment exists already, it will be removed prior to the operation (i.e., overwritten and replaced).

  • insert($name, $content, $parent = null, $before = false) will create a segment named $name. If provided with a $parent segment, the new segment will be placed either before or after that segment (based on the value of $before) in the array. If the segment exists already, it will be removed prior to the operation (i.e., overwritten and replaced).

  • clearBody($name = null) will remove a single named segment if a $name is provided (and the entire array otherwise).

  • getBody($spec = false) can be used to retrieve a single array segment if $spec is the name of a named segment. If $spec is FALSE, it returns a string formed by concatenating all named segments in order. If $spec is TRUE, it returns the body content array.

Testing for Exceptions in the Response Object

As mentioned earlier, by default, exceptions caught during dispatch are registered with the response object. Exceptions are registered in a stack, which allows you to keep all exceptions thrown -- application exceptions, dispatch exceptions, plugin exceptions, etc. Should you wish to check for particular exceptions or to log exceptions, you'll want to use the response object's exception API:

  • setException(Exception $e) allows you to register an exception.

  • isException() will tell you if an exception has been registered.

  • getException() returns the entire exception stack.

  • hasExceptionOfType($type) allows you to determine if an exception of a particular class is in the stack.

  • hasExceptionOfMessage($message) allows you to determine if an exception with a specific message is in the stack.

  • hasExceptionOfCode($code) allows you to determine if an exception with a specific code is in the stack.

  • getExceptionByType($type) allows you to retrieve all exceptions of a specific class from the stack. It will return FALSE if none are found, and an array of exceptions otherwise.

  • getExceptionByMessage($message) allows you to retrieve all exceptions with a specific message from the stack. It will return FALSE if none are found, and an array of exceptions otherwise.

  • getExceptionByCode($code) allows you to retrieve all exceptions with a specific code from the stack. It will return FALSE if none are found, and an array of exceptions otherwise.

  • renderExceptions($flag) allows you to set a flag indicating whether or not exceptions should be emitted when the response is sent.

Subclassing the Response Object

The purpose of the response object is to collect headers and content from the various actions and plugins and return them to the client; secondarily, it also collects any errors (exceptions) that occur in order to process them, return them, or hide them from the end user.

The base response class is Zend_Controller_Response_Abstract, and any subclass you create should extend that class or one of its derivatives. The various methods available have been listed in the previous sections.

Reasons to subclass the response object include modifying how output is returned based on the request environment (e.g., not sending headers for CLI or PHP-GTK requests), adding functionality to return a final view based on content stored in named segments, etc.


Action Helpers