7.9. Das Response Objekt

7.9.1. Verwendung

Das Response Objekt ist das logische Gegenstück zum Request Objekt. Sein Zweck ist es, Inhalte und / oder Header zu vereinigen, um sie in einem Rutsch zu versenden. Zusätzlich übergibt der Front Controller alle aufgefangenen Ausnahmen an das Response Objekt, um dem Entwickler das Verarbeiten von Ausnahmen zu ermöglichen. Dies Funktionalität kann durch Setzen von Zend_Controller_Front::throwExceptions(true) überschrieben werden.

$front->throwExceptions(true);

Um die Ausgabe der Response, inklusiver der gesetzten Header, zu senden, verwendet man sendResponse():

$response->sendResponse();
[Anmerkung] Anmerkung

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

<?php
$front->returnResponse(true);
$response = $front->dispatch();

// do some more processing, such as logging...
// and then send the output:
$response->sendResponse();
?>

Entwickler sollten das Response Objekt in ihren Aktionscontrollern verwenden. Statt die Ausgabe direkt zu machen und Header zu versenden, sollten diese an des Response Objekt übergeben werden:

// Innerhalb einer Controller Aktion:
// Setze einen Header
$this->getResponse()
    ->setHeader('Content-Type', 'text/html')
    ->appendBody($content);

Dadurch werden alle Header in einem Rutsch versendet, genau vor der Anzeige des Inhalts.

[Anmerkung] Anmerkung

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.

Sollte in der Applikation eine Ausnahme auftreten, überprüft man den isException() Schalter des Response Objektes und erhält die Ausnahme durch Verwendung von getException(). Zusätzlich kann man ein eigenes Response Objekt erstellen, dass zu einer Fehlerseite umleitet, die Nachricht der Ausnahme loggt, die Nachricht der Ausnahme schön formatiert ausgibt (für Entwicklungsumgebungen), usw.

Man kann das Response Objekt im Anschluß an die dispatch() Methode des Front Controllers erhalten oder den Front Controller auffordern, dass Response Objekt zurückzugeben statt den Inhalt auszugeben.

// Erhalten nach dem Dispatch:
$front->dispatch();
$response = $front->getResponse();
if ($response->isException()) {
    // log, mail, etc...
}

// Oder den Front Controller dispatch Prozess auffordern, es zurück zu geben
$front->returnResponse(true);
$response = $front->dispatch();

// mache irgend was...

// zum Schluß, gebe die Antwort aus
$response->sendResponse();

Standardmäßig werden Ausnahmennachrichten nicht ausgegeben. Dieses Verhalten kann durch den Aufruf von renderException() überschrieben werden oder indem der Front Controller aufgefordert wird, die Exceptions durch throwExceptions() auszuwerfen, wie oben gezeigt:

$response->renderExceptions(true);
$front->dispatch($request, $response);

// oder:
$front->returnResponse(true);
$response = $front->dispatch();
$response->renderExceptions();
$response->sendResponse();

// oder:
$front->throwExceptions(true);
$front->dispatch();

7.9.2. 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/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/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().

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

<?php
// Assume that this plugin class is registered with the front controller
class MyPlugin extends Zend_Controller_Plugin_Abstract
{
    public function preDispatch(Zend_Controller_Request_Abstract $request)
    {
        $response = $this->getResponse();
        $view = new Zend_View();
        $view->setBasePath('../views/scripts');

        $response->prepend('header', $view->render('header.phtml'));
    }

    public function postDispatch(Zend_Controller_Request_Abstract $request)
    {
        $response = $this->getResponse();
        $view = new Zend_View();
        $view->setBasePath('../views/scripts');

        $response->append('footer', $view->render('footer.phtml'));
    }
}

// a sample action controller
class MyController extends Zend_Controller_Action
{
    public function fooAction()
    {
        $this->render();
    }
}
?>

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

<?php
array(
    'header'  => ..., // header content
    'default' => ..., // body content from MyController::fooAction()
    'footer'  => ...  // footer content
);
?>

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() and appendBody() both allow you to pass a second value, $name, indicating a named segment. In each case, if you provide this, it will overwrite that specific named segment or create it if it does not exist (appending to the array by default). If no named segment is passed to setBody(), it resets the entire body content array. If no named segment is passed to appendBody(), the content is appended to the value in the 'default' name segment.

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

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