Previous Next

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

$front->throwExceptions(true);

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

$response->sendResponse();

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

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

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

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:

// Within an action controller action:
// Set a header
$this->getResponse()
    ->setHeader('Content-Type', 'text/html')
    ->appendBody($content);

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.

// retrieve post-dispatch:
$front->dispatch();
$response = $front->getResponse();
if ($response->isException()) {
    // log, mail, etc...
}

// Or, have the front controller dispatch() process return it
$front->returnResponse(true);
$response = $front->dispatch();

// do some processing...

// finally, echo the response
$response->sendResponse();

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:

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

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

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

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

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:

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

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.

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.

Previous Next
Introdução ao Zend Framework
Resumo
Instalação
Conhecendo o Zend Framework
Guia Rápido do Zend Framework
Zend Framework & MVC Introduction
Create Your Project
Create A Layout
Create a Model and Database Table
Create A Form
Congratulations!
Auto-carregamento no Zend Framework
Introduction
Goals and Design
Basic Autoloader Usage
Resource Autoloading
Conclusion
Plugins no Zend Framework
Introduction
Using Plugins
Conclusion
Iniciando com o Zend_Layout
Introduction
Using Zend_Layout
Zend_Layout: Conclusions
Iniciando com os Marcadores do Zend_View
Introduction
Basic Placeholder Usage
Standard Placeholders
View Placeholders: Conclusion
Entendendo e Usando os Decoradores do Zend Form
Introduction
Decorator Basics
Layering Decorators
Rendering Individual Decorators
Creating and Rendering Composite Elements
Conclusion
Iniciando com o Zend_Session, Zend_Auth, e Zend_Acl
Building Multi-User Applications With Zend Framework
Managing User Sessions In ZF
Authenticating Users in Zend Framework
Building an Authorization System in Zend Framework
Iniciando com o Zend_Search_Lucene
Zend_Search_Lucene Introduction
Lucene Index Structure
Index Opening and Creation
Indexing
Searching
Supported queries
Search result pagination
Iniciando com o Zend_Paginator
Introduction
Simple Examples
Pagination Control and ScrollingStyles
Putting it all Together
Referência do Zend Framework
Zend_Acl
Introduction
Refining Access Controls
Advanced Usage
Zend_Amf
Introdução
Zend_Amf_Server
Zend_Application
Introdução
Zend_Application Quick Start
Theory of Operation
Examples
Core Functionality
Available Resource Plugins
Zend_Auth
Introduction
Database Table Authentication
Digest Authentication
HTTP Authentication Adapter
LDAP Authentication
Open ID Authentication
Zend_Barcode
Introdução
Criação de código de barras usando a classe Zend_Barcode
Objetos Zend_Barcode
Renderizadores do Zend_Barcode
Zend_Cache
Introduction
The Theory of Caching
Zend_Cache Frontends
Zend_Cache Backends
The Cache Manager
Zend_Captcha
Introdução
Captcha Operation
CAPTCHA Adapters
Zend_CodeGenerator
Introduction
Zend_CodeGenerator Examples
Zend_CodeGenerator Reference
Zend_Config
Introdução
Teoria de Operação
Zend_Config_Ini
Zend_Config_Xml
Zend_Config_Writer
Zend_Config_Writer
Zend_Console_Getopt
Introduction
Declaring Getopt Rules
Fetching Options and Arguments
Configuring Zend_Console_Getopt
Zend_Controller
Guia de Início Rápido do Zend_Controller
O Básico de Zend_Controller
O Front Controller
The Request Object
The Standard Router
The Dispatcher
Action Controllers
Action Helpers
The Response Object
Plugins
Using a Conventional Modular Directory Structure
MVC Exceptions
Zend_Currency
Introduction to Zend_Currency
Using Zend_Currency
Options for currencies
What makes a currency?
Where is the currency?
How does the currency look like?
How much is my currency?
Calculating with currencies
Exchanging currencies
Additional informations on Zend_Currency
Zend_Date
Introduction
Theory of Operation
Basic Methods
Zend_Date API Overview
Creation of Dates
Constants for General Date Functions
Working Examples
Zend_Db
Zend_Db_Adapter
Zend_Db_Statement
Zend_Db_Profiler
Zend_Db_Select
Zend_Db_Table
Zend_Db_Table_Row
Zend_Db_Table_Rowset
Zend_Db_Table Relationships
Zend_Db_Table_Definition
Zend_Debug
Dumping Variables
Zend_Dojo
Introduction
Zend_Dojo_Data: dojo.data Envelopes
Dojo View Helpers
Dojo Form Elements and Decorators
Zend_Dojo build layer support
Zend_Dom
Introdução
Zend_Dom_Query
Zend_Exception
Usando as Exceções
Uso básico
Exceções Anteriores
Zend_Feed
Introduction
Importing Feeds
Retrieving Feeds from Web Pages
Consuming an RSS Feed
Consuming an Atom Feed
Consuming a Single Atom Entry
Modifying Feed and Entry structures
Custom Feed and Entry Classes
Zend_Feed_Reader
Zend_Feed_Writer
Zend_Feed_Pubsubhubbub
Zend_File
Zend_File_Transfer
Validators for Zend_File_Transfer
Filters for Zend_File_Transfer
Zend_Filter
Introduction
Standard Filter Classes
Filter Chains
Writing Filters
Zend_Filter_Input
Zend_Filter_Inflector
Zend_Form
Zend_Form
Zend_Form Quick Start
Creating Form Elements Using Zend_Form_Element
Creating Forms Using Zend_Form
Creating Custom Form Markup Using Zend_Form_Decorator
Standard Form Elements Shipped With Zend Framework
Standard Form Decorators Shipped With Zend Framework
Internationalization of Zend_Form
Advanced Zend_Form Usage
Zend_Gdata
Introduction
Authenticating with AuthSub
Using the Book Search Data API
Authenticating with ClientLogin
Using Google Calendar
Using Google Documents List Data API
Using Google Health
Using Google Spreadsheets
Using Google Apps Provisioning
Using Google Base
Using Picasa Web Albums
Using the YouTube Data API
Catching Gdata Exceptions
Zend_Http
Introduction
Zend_Http_Client - Advanced Usage
Zend_Http_Client - Connection Adapters
Zend_Http_Cookie and Zend_Http_CookieJar
Zend_Http_Response
Zend_InfoCard
Introduction
Zend_Json
Introdução
Uso Básico
Uso Avançado do Zend_Json
Conversão de XML para JSON
Zend_Json_Server - JSON-RPC server
Zend_Layout
Introdução
Guia Rápido Zend_Layout
Opções de Configuração Zend_Layout
Uso Avançado de Zend_Layout
Zend_Ldap
Introduction
API overview
Usage Scenarios
Tools
Object oriented access to the LDAP tree using Zend_Ldap_Node
Getting information from the LDAP server
Serializing LDAP data to and from LDIF
Zend_Loader
Loading Files and Classes Dynamically
The Autoloader
Resource Autoloaders
Loading Plugins
Zend_Locale
Introduction
Using Zend_Locale
Normalization and Localization
Working with Dates and Times
Supported locales
Zend_Log
Overview
Writers
Formatters
Filters
Using the Factory to Create a Log
Zend_Mail
Introduction
Sending via SMTP
Sending Multiple Mails per SMTP Connection
Using Different Transports
HTML E-Mail
Attachments
Adding Recipients
Controlling the MIME Boundary
Additional Headers
Character Sets
Encoding
SMTP Authentication
Securing SMTP Transport
Reading Mail Messages
Zend_Markup
Introduction
Getting Started With Zend_Markup
Zend_Markup Parsers
Zend_Markup Renderers
Zend_Measure
Introduction
Creation of Measurements
Outputting measurements
Manipulating Measurements
Types of measurements
Zend_Memory
Overview
Memory Manager
Memory Objects
Zend_Mime
Zend_Mime
Zend_Mime_Message
Zend_Mime_Part
Zend_Navigation
Introduction
Pages
Containers
Zend_Oauth
Introduction to OAuth
Zend_OpenId
Introduction
Zend_OpenId_Consumer Basics
Zend_OpenId_Provider
Zend_Paginator
Introdução
Usage
Configuração
Advanced usage
Zend_Pdf
Introdução.
Criando e Carregando documentos PDF.
Salvar mudanças no documento PDF.
Document pages.
Drawing.
Interactive Features
Informação do Documento e Metadados.
Zend_Pdf module usage example
Zend_ProgressBar
Zend_ProgressBar
Zend_Queue
Introduction
Example usage
Framework
Adapters
Customizing Zend_Queue
Stomp
Zend_Reflection
Introduction
Zend_Reflection Examples
Zend_Reflection Reference
Zend_Registry
Using the Registry
Zend_Rest
Introduction
Zend_Rest_Client
Zend_Rest_Server
Zend_Search_Lucene
Resumo
Construindo Índices
Pesquisando em um Índice
Query Language
Tipos de Consulta
Conjuntos de Caracteres
Extensibilidade
Interoperando com Java Lucene
Advanced
Best Practices
Zend_Serializer
Introduction
Zend_Serializer_Adapter
Zend_Server
Introdução
Zend_Server_Reflection
Zend_Service
Introdução
Zend_Service_Akismet
Zend_Service_Amazon
Zend_Service_Amazon_Ec2
Zend_Service_Amazon_Ec2: Instances
Zend_Service_Amazon_Ec2: Windows Instances
Zend_Service_Amazon_Ec2: Reserved Instances
Zend_Service_Amazon_Ec2: CloudWatch Monitoring
Zend_Service_Amazon_Ec2: Amazon Machine Images (AMI)
Zend_Service_Amazon_Ec2: Elastic Block Storage (EBS)
Zend_Service_Amazon_Ec2: Elastic IP Addresses
Zend_Service_Amazon_Ec2: Keypairs
Zend_Service_Amazon_Ec2: Regions and Availability Zones
Zend_Service_Amazon_Ec2: Security Groups
Zend_Service_Amazon_S3
Zend_Service_Amazon_Sqs
Zend_Service_Audioscrobbler
Zend_Service_Delicious
Zend_Service_DeveloperGarden
Zend_Service_Flickr
Zend_Service_LiveDocx
Zend_Service_Nirvanix
Zend_Service_ReCaptcha
Zend_Service_Simpy
Zend_Service_SlideShare
Zend_Service_StrikeIron
Zend_Service_StrikeIron: Bundled Services
Zend_Service_StrikeIron: Advanced Uses
Zend_Service_Technorati
Zend_Service_Twitter
Zend_Service_WindowsAzure
Zend_Service_Yahoo
Zend_Session
Introduction
Basic Usage
Advanced Usage
Global Session Management
Zend_Session_SaveHandler_DbTable
Zend_Soap
Zend_Soap_Server
Zend_Soap_Client
WSDL Accessor
AutoDiscovery
Zend_Tag
Introduction
Zend_Tag_Cloud
Zend_Test
Introdução
Zend_Test_PHPUnit
Zend_Test_PHPUnit_Db
Zend_Text
Zend_Text_Figlet
Zend_Text_Table
Zend_TimeSync
Introduction
Working with Zend_TimeSync
Zend_Tool
Using Zend_Tool On The Command Line
Extending Zend_Tool
Zend_Tool_Framework
Introduction
Using the CLI Tool
Architecture
Creating Providers to use with Zend_Tool_Framework
Shipped System Providers
Extending and Configuring Zend_Tool_Framework
Zend_Tool_Project
Introduction
Create A Project
Zend_Tool Project Providers
Zend_Tool_Project Internals
Zend_Translate
Introduction
Adapters for Zend_Translate
Using Translation Adapters
Creating source files
Additional features for translation
Plural notations for Translation
Zend_Uri
Zend_Uri
Zend_Validate
Introduction
Standard Validation Classes
Validator Chains
Writing Validators
Validation Messages
Zend_Version
Obtendo a Versão do Zend Framework
Zend_View
Introdução
Scripts Controladores
Scripts de Visualização
Assistentes de Visualização (Modificadores)
Zend_View_Abstract
Zend_Wildfire
Zend_Wildfire
Zend_XmlRpc
Introduction
Zend_XmlRpc_Client
Zend_XmlRpc_Server
ZendX_Console_Process_Unix
ZendX_Console_Process_Unix
ZendX_JQuery
Introduction
ZendX_JQuery View Helpers
ZendX_JQuery Form Elements and Decorators
Pré-requisitos do Zend Framework
Introdução
Notas de Migração do Zend Framework
Zend Framework 1.10
Zend Framework 1.9
Zend Framework 1.8
Zend Framework 1.7
Zend Framework 1.6
Zend Framework 1.5
Zend Framework 1.0
Zend Framework 0.9
Zend Framework 0.8
Zend Framework 0.6
Padrões de Codificação do Framework Zend para PHP
Visão Geral
Formato do Arquivo PHP
Convenções de Nomes
Estilo de Código
Zend Framework Documentation Standard
Overview
Documentation File Formatting
Recommendations
Recommended Project Structure for Zend Framework MVC Applications
Overview
Recommended Project Directory Structure
Module Structure
Rewrite Configuration Guide
Guia de Desempenho do Zend Framework
Introdução
Class Loading
Zend_Db Performance
Internationalization (i18n) and Localization (l10n)
View Rendering
Informações Sobre Direitos Autorais