Notes on Zend Framework by ashrafp


									Notes on Zend Framework
Created 11/22/08
Updated 11/24/08, Updated 11/25/08, Updated 11/26/08, Updated 12/1/08

The Zend Framework (ZF) is an open source framework for developing web applications and services with PHP 5.
ZF is implemented using 100% object-oriented code. The component structure of ZF is somewhat unique; each
component is designed with few dependencies on other components. This loosely coupled architecture allows
developers to use components individually. The framework designers call this a "use-at-will" design.

While they can be used separately, Zend Framework components in the standard library form a powerful and
extensible web application framework when combined. ZF offers a robust and performant MVC implementation,
a database abstraction that is simple to use, and a forms component that implements HTML form rendering,
validation, and filtering so that developers can consolidate all of these operations using one easy-to-use, object
oriented interface. Other components, such as Zend_Auth and Zend_Acl, provide user authentication and
authorization against all common credential stores. Still others implement client libraries to simply access to the
most popular web services available. Whatever your application needs are, you're likely to find a Zend
Framework component that can be used to dramatically reduce development time with a thoroughly tested

In many respects, the Zend Framework is like Java’s Spring framework: it provides a set of components that are
the basis of registry, persistence, presentation, access, and dispatch.

It is at URL The current release is 1.7.0, which came out in September or October

The minimal distribution is 3.98MB compressed, and expands to about 15MB.

The full distribution is about 30MB compressed, and we have not expanded it.

The main resource right now is a 1000 page reference guide available online, or downloadable as a PDF. Since it
is a reference guide, it is arranged alphabetically by class name.

“Zend Framework in Action”, by Rob Allen, Nick Lo, and Steven Brown. Manning Press, December 2008. 425
pages. List price $44.99, Amazon price $29.69, used not available. To be released December 28, 2008.

There are other books about to be released.

This tutorial covers some of ZF's most commonly used components, including Zend_Controller, Zend_Layout,
Zend_Config, Zend_Db, Zend_Db_Table, Zend_Registry, along with a few view helpers.

We had to enable the short tags in the PHP server. They used them in the sample application; though apparently
they don’t in the actual framework code (they have a coding convention against this).

We also need the PDO extension. Had to turn this on, and the corresponding driver for MySQL.

Application structure:

Page 1 of 8
There is nothing special about the project structure above, except some of the MVC components we'll be using
work without overriding defaults if this structure is followed.

        library contains all ZF code
        application:
              o application/controllers: business logic
              o application/views: presentation templates for specific controllers
              o application/models: data objects and persistence facilities
              o application/layouts: master layout files
        public: this contains those files which should be statically served, such as images, css, and JavaScript.
        index.php – this is the main file

Create a Bootstrap File
This file instantiates all of the components (such as the front controller, the configuration), and configurations
them such as the path names for loading and for references. Bootstrap is different from config, as bootstrap
contains definitions that do not change from one deployment to another.

The index file causes the bootstrap file to be loaded

Create an Action Controller & View
To work correctly with the standard router, action method names should follow the lowerCamelCase convention
with the suffix 'Action'. Action controller classes, on the other hand, should follow the UpperCamelCase
convention with the suffix 'Controller'.

This is similar to what we saw in SugarCRM.

While the standard router should work for almost all applications, routing in Zend Framework is completely

Unless otherwise configured, the view it will look for is views/scripts/index/index.phtml, where the
views directory is contained in the same folder as the controllers directory you passed to

Although ZF has its own template engine (is there an example?) that renders templates using a syntax very similar
to standard PHP, you can easily configure Zend Framework to use other template engines such as Smarty or

Page 2 of 8
Create an Error Controller & View
The last things you want to display to an end user of your site are either a blank page or exceptions. Zend
Framework's MVC provides an ErrorHandler plugin that will detect exceptions and dispatch an ErrorController so
that you can easily display appropriate content to your end user.

Additionally, you need some way to handle 404 errors - i.e., situations when the action or controller are not found.
In development, you do want to see exceptions, however. Fortunately, ZF MVC can accommodate both situations.

The ErrorHandler plugin by default will dispatch the errorAction() of the ErrorController. Let's build our

Create a Layout
There are two design patterns that Zend Framework uses to implement layouts: Two Step View and Composite
View. Two Step View is usually associated with the Transform View pattern; the basic idea is that your
application view creates a representation that is then injected into the master view for final transformation. The
Composite View pattern deals with a view made of one or more atomic, application views.

We grab our application content using the layout() view helper, and accessing the "content" key. You may
render to other response segments if you wish to, but in most cases, this is all that's necessary.

Note also the use of the headLink() placeholder. This is an easy way to generate the HTML for <link>
elements, as well as to keep track of them throughout your application. If you need to add additional CSS sheets
to support a single action, you can do so, and be assured it will be present in the final rendered page.

Basically, the layout elements are nested, in the same way that Drupal templates are. One runs inside the other,
and provides content to the caller.

Create a Configuration and Registry
Application configurations are an important part of creating modular and configurable applications. This is where
Zend_Config comes into play. First we will create an application configuration file and put it inside

There is a Registry Manager facility.

Why use the registry instead of globals? Usage of globals is often considered an anti-pattern. Globals are difficult
to test against, as you cannot predict where and when they may be overwritten. A registry can help prevent this,
and also ensure that there is a single location for retrieving objects.

Create a Model and Database Table
For this, we need to enable the PDO extension. This was turned off in our FastStack install.

Then we created:
    models/GuestBook.php - this is like a subclass of SugarBean, and it defines fields and business methods
        on the object. Since the persistence facilities have been moved into models/DbTable objects, this class
        inherits from a generic class
    models/DbTable/GuestBook.php - responsible for persistence (like a DAO, and also called the Table
        Gateway Pattern). It inherits from Zend_Db_Table_Abstract.

The operations on the DAO-like class include:
     insert($record)
     find($key)
     fetchAll($selectWhere, $groupBy, $limitStart, $limitPageSize) – often the where clause is given as “1”,
        which means all. Apparently this cannot be null.

Page 3 of 8
        fetchRow($select)
        update($record, $where)
        delete($where)

You can allow JOIN clauses on a select to allow multi-table lookups.

You can not specify columns from a JOINed table to be returned in a row/rowset. Doing so will trigger a PHP
error. This was done to ensure the integrity of the Zend_Db_Table is retained. i.e. A
Zend_Db_Table_Row should only reference columns derived from its parent table.
However there may be certain cases where you require the flexibility of the Zend_Db_Table_Row component and
do not require a writable or deletable row. For this specific user case, it is possible to retrieve a row/rowset by
passing a false value to setIntegrityCheck. The resulting row/rowset will be returned as a 'locked' row (meaning
the save(), delete() and any field-setting methods will throw an exception).

$table = new Bugs();

$select = $table->select()->setIntegrityCheck(false);
$select->where('bug_status = ?', 'NEW')
              'accounts.account_name = bugs.reported_by',
       ->where('accounts.account_name = ?', 'Bob');

$rows = $table->fetchAll($select);

Create a Form
This class inherits from ZendForm, and contains a set of specifications that define the fields to be displayed and
processed. You can also specify validation here.

Summary of Steps
You are done! Well, that was pretty tough. Also, I didn’t really like the directory structure that was built – it
appears that if we had 3 classes, their modules, controllers, models and views would be scattered into three
different places for a 3x3 grid of folders.


Model-View-Controller (MVC)
        Zend_Controller, Zend_Controller_Action, Zend_Controller_Dispatcher, Zend_Controller_Plugin,
         Zend_Controller_RewriteRouter, Zend_View

        Zend_Http_Request, Zend_Http_Response
The above components make use of the industry standard web application design pattern MVC, and allows
developers and web designers to separate their concerns and skills, making code implementation and design easily
and clearly separated. No more confusion or needing both skill sets in one person.

        Zend_Db

        Zend_Db_Table

Page 4 of 8
Again using standard database programming best practices, data adapters for all major databases abstract away the
details, so you can build your application (domain of your business) models on whatever database engine you

Internationalization (i18n) and Localization (l10n)
        Zend_Date

        Zend_Locale

        Zend_Measure

        Zend_Translate
In an increasingly global economy, localizing your application for a particular language and culture is imperative,
not an afterthought. Do that easily, whenever you're ready to expand your markets, with Zend Framework's
support for internationalization (i18n).

Authentication, Authorization, and Session management
        Zend_Acl

        Zend_Authentication

        Zend_Session
Virtually all web applications have some user-specific data that must be customized, and usually, protected from
access by other users. Accomplish this quickly and easily with the above features of Zend Framework.

Web and Web Services
        Consuming services: Zend_Feed, Zend_Rest_Client, Zend_Service, Zend_XmlRpc_Client, Zend_Gdata,

        Exposing services: Zend_Http_Server, Zend_Rest_Server, Zend_Server_Documentor,
         Zend_Server_Reflection, Zend_Soap_Server, Zend_XmlRpc_Server

        Zend_Uri
Web services are an integral part of Zend Framework and we intend for Zend Framework to be the nexus for and
entire eco-system of Web Services and APIs providers. Zend has currently partnered with Google, Microsoft, and
StrikeIron and they have built support for their services into Zend Framework. More are coming soon.

Mail, Formats, and Search
        Zend_Json, Zend_Pdf

        Zend_Mail, Zend_Mime

        Zend_Search_Lucene
Web 2.0 applications require support for Ajax, PDF generation, e-mail communication, and search, all an
increasingly important part of web applications today. Zend Framework simplifies a developers life and gives you
built-in support for these essential, if not critical, features for your application.

Core Infrastructure
        Zend_Cache, Zend_Config, Zend_Console_Getopt, Zend_Log, Zend_Memory

Page 5 of 8
        Zend_Debug, Zend_Environment, Zend_Loader, Zend_Registry, Zend_Version

        Zend_Filter, Zend_Validate
Zend Framework is a broad library of loosely-coupled, yet highly cohesive pieces that support many of the other
features you might need for a web application. From logging for tracking and debugging your application in
production, caching for high performance, filtering for more secure and safe applications, to all the other little
pieces that make a web application developer's life easy, Zend Framework provides all this, plus a vast
community, a company standing behind and sponsoring development, and a large number of talented developers
who know how to build Zend Framework applications from the ground up.

Examples of Use
Recently an email was sent to the Zend Framework General List that mentioned the fact that there are now
several projects on SourceForge based on the Zend Framework. There are actually 7,187 projects if you just
search for Zend Framework but if you put search for Zend Framework in quotes, we get down to the 17 we
really want. Here is a rundown of most of them.

Teknologiaplaneetta – Enterprise Solution is a ready made system to start to make your own web-based
software just only a developing modules for under its framework. Framework uses Zend Framework and some
JavaScript and AJAX.

Blt-3 is a Web framework built onto the Zend Framework and Dojo Toolkit. Main (and first) modules are the
security management and a workflow.

phpYabs (Yet Another Books Software) is an Object-Oriented application written for php5 and based on Zend
Framework its goal is to provide a simple interface to manage either a personal book library or a book store.

Astrum Futura – Multiplayer space strategy game written in PHP5 with the Zend Framework. User interface
uses Javascript/AJAX for dynamic interaction. Players compete across a hexagonal map of 10,000 sectors,
planets, stars and other locations through trade and combat.

Luta framework – is a PHP 5 framework based on Zend Framework with Ruby on Rails like architecture.

Bidule is a implementation of Zend Framework

ZFWeb20 – is the open source web application build on Zend Framework v1.0 ( It’s
main purposes is to deliver common use tools like blog, cms, picture gallery to any user who will want to create
his own Web 2.0 website.

Brother Jonathan is a cross-platform ERP/MRP package coded in PHP, allowing small manufacturers to manage
custom jobs. Built on the Zend Framework in an easily extensible manner with modules for quotes, sales orders,
purchase orders, and invoices, etc.

HappyCMS is an OpenSource CMS based on Zend Framework, which is a new OO PHP5 Framework.Developers
can easily create Plug-Ins to extend the Program and change the themes. HappyCMS will build more useful
modules in the future.

Orca is a web-based call center platform written in PHP 5 / Javascript using the Zend Framework, JQuery and
Asterisk, utilizing these frameworks will allow for a more reliable platform and focus can be placed on innovation
and not re-creation.

OpenBay PHP Auction Auction software built with the Zend Framework, PHP5 and MySQL. OpenBay is a
modern XHTML/CSS compliant web application that is highly customizable and easy to install and use.

Page 6 of 8
Octane Project – Quickly create and customize your own website with this intuitive content management and
portal system. While designed to be streamlined and powerful, Octane provides versatility, powered by the Zend
Framework and backed by the Smarty Template Engine. Unfortunately no code has been released yet.

DevTeams is a web-based project management system designed primarily, but not exclusively, for developement
teams that need to coordinate many projects with different clients. It is built on top of emerging Zend Framework.

ZF CMS – CMS based on Zend Framework

Tipos is a PHP publishing tool and a base system to create web applications. It is built using the Zend Framework
and has a powerful plug-in system to which you can attach anything: a blog, podcast, news or links manager, a
FAQ, a forum or all of these.

ZF CMS as an Example
This was a simple implementation on SourceForge written in 2005, but it appears to be updated through early 2008
(the code is now on Google code at The download
is 1.98MB which expands to about 3.54 MB. However, this doesn’t appear to include Zend or Smarty.

ZF CMS uses TinyMCE and Smarty.

Digitalus CMS as an Example
This is written up in the APress book “Pro Zend Framework CMS: Building a Full CMS Using Advanced Aspects
of the Zend Framework” by Forest Lyman, which will be released in April 2009.

Under the hood the CMS follows Zend’s convention using their MVC paradigm and is based (loosely) on their
conventional modular structure. There are several notable exceptions, such as separating all of the add-on
modules (news, events, galleries, custom modules) from the core CMS to avoid confusing these files and the core.

CMS developers (with strong object oriented PHP skills) will find the system flexible and intuitive to develop and
maintain. The skill set required to get the most out of the system is exactly the same as is required to develop with
the Zend Framework, so any experience gained in the CMS will be applicable to any ZF based projects.

On the front end (admin and site) the CMS has a powerful template system which is built on Zend View, Zend
Layout, and Jquery with a strong focus on valid XHTML.

This is undergoing current development at

We have a download of version 1.01 from April 2008. Apparently 1.5 will be out in December.

The download is about 5M. This expands to about 18MB, of which Zend is about 13MB. Since the current
minimal Zend is about 15MB, this implies that it either isn’t a complete minimal distribution, or it is an earlier

The structure matches the demo that we saw earlier today. It also includes use of jQuery and FCKEditor.
Their subordinate library is called DSF. There is a great deal of work and a large number of files in this package!

Create a new database named what ever you want. Locate the digitalus_cms.sql file (located in
/application/data/...). Run this db dump on your new database.

Classes that we have used
Zend_Controller_Front – this acts as a front dispatcher, and is a singleton. Get it by calling getInstance().

Page 7 of 8
Zend_Layout – creates a parent layout for output, and also returns the View object.

Zend_Configuration_Ini – reads the configuration from an ini file

Zend_DB – returns a db_adapter from a factory method.

Zend_DB_Table – gets told what adapter to use

Zend_Registry – gets an instance, and that instance is told the db adapter and the configuration

Zend_Controller_Action – the superclass of all action classes.

Open Issues in Learning and Using the Zend Framework
What are some of the supporting classes that would make it easy to define ListViews, DetailViews, and
EditViews? How about a module system?

How about a data table with paging and sorting? See

How could the model objects be generalized to use something like vardefs?

How about a set of tabs?

How well is the data access generalized? Since there doesn’t seem to be a vardefs file, it appears that
configuration decisions are present in schema files, data access files, and presentation templates.

Page 8 of 8

To top