Previous Next

Zend_Dojo build layer support

Introduction

Dojo build layers provide a clean path from development to production when using Dojo for your UI layer. In development, you can have load-on-demand, rapid application prototyping; a build layer takes all Dojo dependencies and compiles them to a single file, optionally stripping whitespace and comments, and performing code heuristics to allow further minification of variable names. Additionally, it can do CSS minification.

In order to create a build layer, you would traditionally create a JavaScript file that has dojo.require statements for each dependency, and optionally some additional code that might run when the script is loaded. As an example:

dojo.provide("custom.main");

dojo.require("dijit.layout.TabContainer");
dojo.require("dijit.layout.ContentPane");
dojo.require("dijit.form.Form");
dojo.require("dijit.form.Button");
dojo.require("dijit.form.TextBox");

This script is generally referred to as a "layer" script.

Then, in your application's layout, you'd instruct Dojo to load this module:



    
    

If you use Zend_Dojo to do this, you'd do the following:

$view->dojo()->registerModulePath('custom', '../custom/')
             ->requireModule('custom.main');

But since Zend_Dojo aggregates your various dojo.require statements, how do you create your layer script? You could open each page and view the generated dojo.require statements, and cut and paste them into a layer script file manually.

However, a better solution exists: since Zend_Dojo aggregates this information already, you can simply pull that information and build your layer file. This is the purpose of Zend_Dojo_BuildLayer.

Generating Custom Module Layers with Zend_Dojo_BuildLayer

At its simplest, you simply instantiate Zend_Dojo_BuildLayer, feed it the view object and the name of your custom module layer, and have it generate the content of the layer file; it is up to you to then write it to disk.

As an example, let's say you wanted to create the module layer "custom.main". Assuming you follow the recommended project directory structure, and that you are storing your JavaScript files under public/js/, you could do the following:

$build = new Zend_Dojo_BuildLayer(array(
    'view'      => $view,
    'layerName' => 'custom.main',
));

$layerContents = $build->generateLayerScript();
$filename      = APPLICATION_PATH . '/../public/js/custom/main.js';
if (!dir_exists(dirname($filename))) {
    mkdir(dirname($filename));
}
file_put_contents($filename, $layerContents);

When should you do the above? For it to work correctly, you need to do it after all view scripts and the layout have been rendered, to ensure that the dojo() helper is fully populated. One easy way to do so is using a front controller plugin, with a dispatchLoopShutdown() hook:

class App_Plugin_DojoLayer extends Zend_Controller_Plugin_Abstract
{
    public $layerScript = APPLICATION_PATH . '/../public/js/custom/main.js';
    protected $_build;

    public function dispatchLoopShutdown()
    {
        if (!file_exists($this->layerScript)) {
            $this->generateDojoLayer();
        }
    }

    public function getBuild()
    {
        $viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper(
            'ViewRenderer'
        );
        $viewRenderer->initView();
        if (null === $this->_build) {
            $this->_build = new Zend_Dojo_BuildLayer(array(
                'view'      => $viewRenderer->view,
                'layerName' => 'custom.main',
            ));
        }
        return $this->_build;
    }

    public function generateDojoLayer()
    {
        $build = $this->getBuild();
        $layerContents = $build->generateLayerScript();
        if (!dir_exists(dirname($this->layerScript))) {
            mkdir(dirname($this->layerScript));
        }
        file_put_contents($this->layerScript, $layerContents);
    }
}

Note: Do not generate the layer on every page

It's tempting to generate the layer script on each and every page. However, this is resource intensive, as it must write to the disk on each page. Additionally, since the mtime of the file will keep changing, you will get no benefits of client-side caching. Write the file once.

BuildLayer options

The above functionality will suffice for most situations. For those needing more customization, a variety of options may be invoked.

Setting the view object

While the view object may be passed during instantiation, you may also pass it in to an instance via the setView() method:

$build->setView($view);

Setting the layer name

While the layer name may be passed during instantiation, you may also pass it in to an instance via the setLayerName() method:

$build->setLayerName("custom.main");

Including onLoad events in the generated layer

dojo.addOnLoad is a useful utility for specifying actions that should trigger when the DOM has finished loading. The dojo() view helper can create these statements via its addOnLoad() and onLoadCapture() methods. In some cases, it makes sense to push these into your layer file instead of rendering them via your view scripts.

By default, these are not rendered; to enable them, pass the consumeOnLoad configuration key during instantiation:

$build = new Zend_Dojo_BuildLayer(array(
    'view'          => $view,
    'layerName'     => 'custom.main',
    'consumeOnLoad' => true,
));

Alternately, you can use the setConsumeOnLoad() method after instantiation:

$build->setConsumeOnLoad(true);

Including captured JavaScript in the generated layer

The dojo() view helper includes methods for capturing arbitrary JavaScript to include in the <script> tag containing the various dojo.require and dojo.addOnLoad statements. This can be useful when creating default data stores or globally scoped objects used throughout your application.

By default, these are not rendered; to enable them, pass the consumeJavascript configuration key during instantiation:

$build = new Zend_Dojo_BuildLayer(array(
    'view'              => $view,
    'layerName'         => 'custom.main',
    'consumeJavascript' => true,
));

Alternately, you can use the setConsumeJavascript() method after instantiation:

$build->setConsumeJavascript(true);

Generating Build Profiles with Zend_Dojo_BuildLayer

One of the chief benefits of a Dojo module layer is that it facilitates the creation of a custom build. Zend_Dojo_BuildLayer has functionality for generate build profiles.

The simplest use case is to utilize the generateBuildProfile() method and send the output to a file:

$build = new Zend_Dojo_BuildLayer(array(
    'view'      => $view,
    'layerName' => 'custom.main',
));

$profile   = $build->generateBuildProfile();
$filename  = APPLICATION_PATH . '/../misc/scripts/custom.profile.js';
file_put_contents($filename, $profile);

Just like generating layers, you may want to automate this via a dispatchLoopShutdown() plugin hook; you could even simply modify the one shown for generating layers to read as follows:

class App_Plugin_DojoLayer extends Zend_Controller_Plugin_Abstract
{
    public $layerScript  = APPLICATION_PATH
                         . '/../public/js/custom/main.js';
    public $buildProfile = APPLICATION_PATH
                         . '/../misc/scripts/custom.profile.js';
    protected $_build;

    public function dispatchLoopShutdown()
    {
        if (!file_exists($this->layerScript)) {
            $this->generateDojoLayer();
        }
        if (!file_exists($this->buildProfile)) {
            $this->generateBuildProfile();
        }
    }

    public function generateDojoLayer() { /* ... */ }

    public function generateBuildProfile()
    {
        $profile = $this->getBuild()->generateBuildProfile();
        file_put_contents($this->buildProfile, $profile);
    }

}

As noted, with module layers, you should only create the file once.

Build Profile options

The above functionality will suffice for most situations. The only way to customize build profile generation is to provide additional build profile options to utilize.

As an example, you may want to specify what type of optimizations should be performed, whether or not to optimize CSS files in the layer, whether or not to copy tests into the build, etc. For a listing of available options, you should read the » Dojo Build documentation and » accompanying documentation.

Setting these options is trivial: use the addProfileOption(), addProfileOptions(), or setProfileOptions() methods. The first method adds a single key and value option pair, the second will add several, and the third will overwrite any options with the list of key and value pairs provided.

By default, the following options are set:

{
    action:        "release",
    optimize:      "shrinksafe",
    layerOptimize: "shrinksafe",
    copyTests:     false,
    loader:        "default",
    cssOptimize:   "comments"
}

You can pass in whatever key and value pairs you want; the Dojo build script will ignore those it does not understand.

As an example of setting options:

// A single option:
$build->addProfileOption('version', 'zend-1.3.1');

// Several options:
$build->addProfileOptions(array(
    'loader'   => 'xdomain',
    'optimize' => 'packer',
));

// Or overwrite options:
$build->setProfileOptions(array(
    'version'  => 'custom-1.3.1',
    'loader'   => 'shrinksafe',
    'optimize' => 'shrinksafe',
));
Previous Next
Introduction to Zend Framework
Overview
Installation
Learning Zend Framework
Zend Framework Quick Start
Zend Framework & MVC Introduction
Create Your Project
Create A Layout
Create a Model and Database Table
Create A Form
Congratulations!
Autoloading in Zend Framework
Introduction
Goals and Design
Basic Autoloader Usage
Resource Autoloading
Conclusion
Plugins in Zend Framework
Introduction
Using Plugins
Conclusion
Getting Started with Zend_Layout
Introduction
Using Zend_Layout
Zend_Layout: Conclusions
Getting Started Zend_View Placeholders
Introduction
Basic Placeholder Usage
Standard Placeholders
View Placeholders: Conclusion
Understanding and Using Zend Form Decorators
Introduction
Decorator Basics
Layering Decorators
Rendering Individual Decorators
Creating and Rendering Composite Elements
Conclusion
Getting Started with 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
Getting Started with Zend_Search_Lucene
Zend_Search_Lucene Introduction
Lucene Index Structure
Index Opening and Creation
Indexing
Searching
Supported queries
Search result pagination
Getting Started with Zend_Paginator
Introduction
Simple Examples
Pagination Control and ScrollingStyles
Putting it all Together
Zend Framework Reference
Zend_Acl
Introduction
Refining Access Controls
Advanced Usage
Zend_Amf
Introduction
Zend_Amf_Server
Zend_Application
Introduction
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
Introduction
Barcode creation using Zend_Barcode class
Zend_Barcode Objects
Zend_Barcode Renderers
Zend_Cache
Introduction
The Theory of Caching
Zend_Cache Frontends
Zend_Cache Backends
The Cache Manager
Zend_Captcha
Introduction
Captcha Operation
CAPTCHA Adapters
Zend_CodeGenerator
Introduction
Zend_CodeGenerator Examples
Zend_CodeGenerator Reference
Zend_Config
Introduction
Theory of Operation
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
Zend_Controller Quick Start
Zend_Controller Basics
The 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
Introduction
Zend_Dom_Query
Zend_Exception
Using Exceptions
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
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
Introduction
Basic Usage
Advanced Usage of Zend_Json
XML to JSON conversion
Zend_Json_Server - JSON-RPC server
Zend_Layout
Introduction
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
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
Introduction
Usage
Configuration
Advanced usage
Zend_Pdf
Introduction
Creating and Loading PDF Documents
Save Changes to PDF Documents
Working with Pages
Drawing
Interactive Features
Document Info and Metadata
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
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_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
Introduction
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
Getting the Zend Framework Version
Zend_View
Introduction
Controller Scripts
View Scripts
View Helpers
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
Zend Framework Requirements
Introduction
Zend Framework Migration Notes
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
Zend Framework Coding Standard for PHP
Overview
PHP File Formatting
Naming Conventions
Coding Style
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
Zend Framework Performance Guide
Introduction
Class Loading
Zend_Db Performance
Internationalization (i18n) and Localization (l10n)
View Rendering
Copyright Information