Previous Next

View Rendering

When using Zend Framework's MVC layer, chances are you will be using Zend_View. Zend_View is performs well compared to other view or templating engines; since view scripts are written in PHP, you do not incur the overhead of compiling custom markup to PHP, nor do you need to worry that the compiled PHP is not optimized. However, Zend_View presents its own issues: extension is done via overloading (view helpers), and a number of view helpers, while carrying out key functionality do so with a performance cost.

How can I speed up resolution of view helpers?

Most Zend_View "methods" are actually provided via overloading to the helper system. This provides important flexibility to Zend_View; instead of needing to extend Zend_View and provide all the helper methods you may utilize in your application, you can define your helper methods in separate classes and consume them at will as if they were direct methods of Zend_View. This keeps the view object itself relatively thin, and ensures that objects are created only when needed.

Internally, Zend_View uses the PluginLoader to look up helper classes. This means that for each helper you call, Zend_View needs to pass the helper name to the PluginLoader, which then needs to determine the class name, load the class file if necessary, and then return the class name so it may be instantiated. Subsequent uses of the helper are much faster, as Zend_View keeps an internal registry of loaded helpers, but if you use many helpers, the calls add up.

The question, then, is: how can you speed up helper resolution?

Use the PluginLoader include file cache

The simplest, cheapest solution is the same as for general PluginLoader performance: use the PluginLoader include file cache. Anecdotal evidence has shown this technique to provide a 25-30% performance gain on systems without an opcode cache, and a 40-65% gain on systems with an opcode cache.

Extend Zend_View to provide often used helper methods

Another solution for those seeking to tune performance even further is to extend Zend_View to manually add the helper methods they most use in their application. Such helper methods may simply manually instantiate the appropriate helper class and proxy to it, or stuff the full helper implementation into the method.

class My_View extends Zend_View
{
    /**
     * @var array Registry of helper classes used
     */
    protected $_localHelperObjects = array();

    /**
     * Proxy to url view helper
     *
     * @param  array $urlOptions Options passed to the assemble method
     *                           of the Route object.
     * @param  mixed $name The name of a Route to use. If null it will
     *                     use the current Route
     * @param  bool $reset Whether or not to reset the route defaults
     *                     with those provided
     * @return string Url for the link href attribute.
     */
    public function url(array $urlOptions = array(), $name = null,
        $reset = false, $encode = true
    ) {
        if (!array_key_exists('url', $this->_localHelperObjects)) {
            $this->_localHelperObjects['url'] = new Zend_View_Helper_Url();
            $this->_localHelperObjects['url']->setView($this);
        }
        $helper = $this->_localHelperObjects['url'];
        return $helper->url($urlOptions, $name, $reset, $encode);
    }

    /**
     * Echo a message
     *
     * Direct implementation.
     *
     * @param  string $string
     * @return string
     */
    public function message($string)
    {
        return "

" . $this->escape($message) . "

\n"; } }

Either way, this technique will substantially reduce the overhead of the helper system by avoiding calls to the PluginLoader entirely, and either benefiting from autoloading or bypassing it altogether.

How can I speed up view partials?

Those who use partials heavily and who profile their applications will often immediately notice that the partial() view helper incurs a lot of overhead, due to the need to clone the view object. Is it possible to speed this up?

Use partial() only when really necessary

The partial() view helper accepts three arguments:

  • $name: the name of the view script to render

  • $module: the name of the module in which the view script resides; or, if no third argument is provided and this is an array or object, it will be the $model argument.

  • $model: an array or object to pass to the partial representing the clean data to assign to the view.

The power and use of partial() come from the second and third arguments. The $module argument allows partial() to temporarily add a script path for the given module so that the partial view script will resolve to that module; the $model argument allows you to explicitly pass variables for use with the partial view. If you're not passing either argument, use render() instead!

Basically, unless you are actually passing variables to the partial and need the clean variable scope, or rendering a view script from another MVC module, there is no reason to incur the overhead of partial(); instead, use Zend_View's built-in render() method to render the view script.

How can I speed up calls to the action() view helper?

Version 1.5.0 introduced the action() view helper, which allows you to dispatch an MVC action and capture its rendered content. This provides an important step towards the DRY principle, and promotes code reuse. However, as those who profile their applications will quickly realize, it, too, is an expensive operation. Internally, the action() view helper needs to clone new request and response objects, invoke the dispatcher, invoke the requested controller and action, etc.

How can you speed it up?

Use the ActionStack when possible

Introduced at the same time as the action() view helper, the ActionStack consists of an action helper and a front controller plugin. Together, they allow you to push additional actions to invoke during the dispatch cycle onto a stack. If you are calling action() from your layout view scripts, you may want to instead use the ActionStack, and render your views to discrete response segments. As an example, you could write a dispatchLoopStartup() plugin like the following to add a login form box to each page:

class LoginPlugin extends Zend_Controller_Plugin_Abstract
{
    protected $_stack;

    public function dispatchLoopStartup(
        Zend_Controller_Request_Abstract $request
    ) {
        $stack = $this->getStack();
        $loginRequest = new Zend_Controller_Request_Simple();
        $loginRequest->setControllerName('user')
                     ->setActionName('index')
                     ->setParam('responseSegment', 'login');
        $stack->pushStack($loginRequest);
    }

    public function getStack()
    {
        if (null === $this->_stack) {
            $front = Zend_Controller_Front::getInstance();
            if (!$front->hasPlugin('Zend_Controller_Plugin_ActionStack')) {
                $stack = new Zend_Controller_Plugin_ActionStack();
                $front->registerPlugin($stack);
            } else {
                $stack = $front->getPlugin('ActionStack')
            }
            $this->_stack = $stack;
        }
        return $this->_stack;
    }
}

The UserController::indexAction() method might then use the $responseSegment parameter to indicate which response segment to render to. In the layout script, you would then simply render that response segment:

layout()->login ?>

While the ActionStack still requires a dispatch cycle, this is still cheaper than the action() view helper as it does not need to clone objects and reset internal state. Additionally, it ensures that all pre and post dispatch plugins are invoked, which may be of particular concern if you are using front controller plugins for handling ACL's to particular actions.

Favor helpers that query the model over action()

In most cases, using action() is simply overkill. If you have most business logic nested in your models and are simply querying the model and passing the results to a view script, it will typically be faster and cleaner to simply write a view helper that pulls the model, queries it, and does something with that information.

As an example, consider the following controller action and view script:

class BugController extends Zend_Controller_Action
{
    public function listAction()
    {
        $model = new Bug();
        $this->view->bugs = $model->fetchActive();
    }
}

// bug/list.phtml:
echo "
    \n"; foreach ($this->bugs as $bug) { printf("
  • %s: %s
  • \n", $this->escape($bug->id), $this->escape($bug->summary) ); } echo "
\n";

Using action(), you would then invoke it with the following:

action('list', 'bug') ?>

This could be refactored to a view helper that looks like the following:

class My_View_Helper_BugList extends Zend_View_Helper_Abstract
{
    public function bugList()
    {
        $model = new Bug();
        $html  = "
    \n"; foreach ($model->fetchActive() as $bug) { $html .= sprintf( "
  • %s: %s
  • \n", $this->view->escape($bug->id), $this->view->escape($bug->summary) ); } $html .= "
\n"; return $html; } }

You would then invoke the helper as follows:

bugList() ?>

This has two benefits: it no longer incurs the overhead of the action() view helper, and also presents a more semantically understandable API.

Previous Next
Introducción a Zend Framework
Descripción general
Instalación
Aprendiendo Zend Framework
Inicio Rápido con Zend Framework
Introducción a MVC & ZF
Create Your Project
Create A Layout
Create a Model and Database Table
Create A Form
¡Felicitaciones!
Autocarga o Carga automática en Zend Framework
Introduction
Goals and Design
Basic Autoloader Usage
Resource Autoloading
Conclusion
Plugins en Zend Framework
Introduction
Using Plugins
Conclusion
Primeros pasos con Zend_Layout
Introduction
Using Zend_Layout
Zend_Layout: Conclusions
Introducción a Zend_View Placeholders
Introduction
Basic Placeholder Usage
Standard Placeholders
View Placeholders: Conclusion
Comprensión y uso de Zend Form Decorators
Introduction
Decorator Basics
Layering Decorators
Rendering Individual Decorators
Creating and Rendering Composite Elements
Conclusión
Primeros pasos con Zend_Session, Zend_Auth, and 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
Primeros pasos con Zend_Search_Lucene
Zend_Search_Lucene Introduction
Lucene Index Structure
Index Opening and Creation
Indexing
Searching
Supported queries
Search result pagination
Primeros pasos con Zend_Paginator
Introduction
Simple Examples
Pagination Control and ScrollingStyles
Putting it all Together
Referencia de Zend Framework
Zend_Acl
Introducción
Perfeccionamiento de los controles de acceso
Uso Avanzado
Zend_Amf
Introducción
Zend_Amf_Server
Zend_Application
Introducción
Inicio rápido con Zend_Application
Teoría de Operación
Ejemplos
Funcionalidad Básica
Plugins de Recursos Disponibles
Zend_Auth
Introducción
Tabla de base de datos de autenticación
Autenticación "Digest"
Adaptador de Autenticación HTTP
LDAP Authentication
Autenticación con Open ID
Zend_Barcode
Introduction
Barcode creation using Zend_Barcode class
Zend_Barcode Objects
Zend_Barcode Renderers
Zend_Cache
Introducción
The Theory of Caching
Zend_Cache Frontends
Zend_Cache Backends
The Cache Manager
Zend_Captcha
Introducción
Captcha Operation
CAPTCHA Adapters
SimpleCloud API: Zend_Cloud
Document Service Introduction
Queue Service Introduction
StorageService Introduction
Zend_CodeGenerator
Introducción
Ejemplos de Zend_CodeGenerator
Referencias de Zend_CodeGenerator
Zend_Config
Introducción
Aspectos Teóricos
Zend_Config_Ini
Zend_Config_Json
Zend_Config_Xml
Zend_Config_Yaml
Zend_Config_Writer
Zend_Config_Writer
Zend_Console_Getopt
Introduction
Declaring Getopt Rules
Fetching Options and Arguments
Configuring Zend_Console_Getopt
Zend_Controller
Inicio rápido a Zend_Controller
Conceptos Básicos de Zend_Controller
El Front Controller
La solicitud del Objeto
El Router Standard
El Despachador
Controladores de Acción
Action Helpers
The Response Object
Plugins
Using a Conventional Modular Directory Structure
Excepciones MVC
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
Introducción
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
Mostrar información de variables(Dumping Variables)
Zend_Dojo
Introducción
Zend_Dojo_Data: Envolturas de dojo.data
Ayudantes de Dojo View
Elementos y Decoradores de Dojo Form
Zend_Dojo build layer support
Zend_Dom
Introducción
Zend_Dom_Query
Zend_Exception
Uso de Excepciones
Basic usage
Previous Exceptions
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
Introducción
Standard Filter Classes
Filter Chains
Writing Filters
Zend_Filter_Input
Zend_Filter_Inflector
Zend_Form
Zend_Form
Inicio rápido a Zend_Form
Creando elementos de formulario usando Zend_Form_Element
Creando formularios usando Zend_Form
Creando un personalizado marcado de formulario usando Zend_Form_Decorator
Elementos Enviados en el Formulario Estandard de Zend Framework
Decoradores de Formulario (Form Decorartors) estándar contenidos en Zend Framework
Internacionalización de Zend_Form
Uso avanzado de Zend_Form
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_Http_UserAgent
The UserAgent Device Interface
The UserAgent Features Adapter
The WURFL UserAgent Features Adapter
The DeviceAtlas UserAgent Features Adapter
The TeraWurfl UserAgent Features Adapter
The UserAgent Storage Interface
The Session UserAgent Storage Adapter
Zend_InfoCard
Introduction
Zend_Json
Introducción
Uso Básico
Uso Avanzado de Zend_Json
Conversión de XML a JSON
Zend_Json_Server - servidor JSON-RPC
Zend_Layout
Introducción
Zend_Layout Quick Start
Zend_Layout Configuration Options
Zend_Layout Advanced Usage
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
Cargando archivos y clases dinámicamente
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
Introduction
Usage
Configuration
Advanced usage
Zend_Pdf
Introducción
Creando y Cargando Documentos PDF
Guardar Cambios a Documentos PDF
Trabajando con Páginas
Dibujo
Interactive Features
Información del Documento y Metadatos
Ejemplo de Uso del módulo Zend_Pdf
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
Overview
Building Indexes
Searching an Index
Query Language
Query Construction API
Character Set
Extensibility
Interoperating with Java Lucene
Advanced
Best Practices
Zend_Serializer
Introduction
Zend_Serializer_Adapter
Zend_Server
Introduction
Zend_Server_Reflection
Zend_Service
Introduction
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_Ebay
Zend_Service_Ebay_Finding
Zend_Service_Flickr
Zend_Service_LiveDocx
Zend_Service_Nirvanix
Zend_Service_ReCaptcha
Zend_Service_ShortUrl
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_WindowsAzure_Storage_Blob
Zend_Service_WindowsAzure_Diagnostics_Manager
Zend_Service_WindowsAzure_Storage_Queue
Zend_Service_WindowsAzure_Storage_Table
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
Introducción
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
Usando la herramienta CLI
Architecture
Creando Proveedores para usar con 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 Internos
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
Introducción
Clases de Validación Estándar
Cadenas de Validadores
Escribiendo Validadores
Validation Messages
Zend_Version
Obteniendo la versión de Zend Framework Version
Zend_View
Introduction
Controller Scripts
View Scripts
View Helpers
Zend_View_Abstract
Zend_Wildfire
Zend_Wildfire
Zend_XmlRpc
Introducción
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
Requisitos de Zend Framework
Versión de PHP
Extensiones de PHP
Componentes de Zend Framework
Dependencias de Zend Framework
Notas de Migración de 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
Estándares de codificación de Zend Framework para PHP
Introducción
Formato de archivos PHP
Convenciones de Nombres
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
Guía de Rendimiento de Zend Framework
Introduction
Class Loading
Zend_Db Performance
Internationalization (i18n) and Localization (l10n)
View Rendering
Copyright Information