Zend Framework Intro
— print (last updated: Sep 15, 2009) print

Select font size:

Zend Web Framework

The Zend Web Framework is but one of a large number of web frameworks. These are software tools which support the construction of web sites by focusing on some or all of these features Web frameworks are often grouped together with Content Management Systems (CMS). Both rely upon an underlying programming language and a DBMS as a basis. The focus of CMSs is more on content creation through template-like constructions rather than HTML construction and programming. Both Web Frameworks and Content Management Systems can be used to automate the building of large complex websites, but CMSs are usually simpler to use and often a better choice for the non-programmer, but ultimately, less flexible than a web framework. A blog is a certain specialized version of a Content Management System (CMS) which usually has a fixed backend database and offers greater simplicity in usage by virtue of restricting the possible presentations even further.

The "bar-setter" for web frameworks is probably still Ruby-on-Rails, although it has come under criticism for the lack of development and performance of the underlying Ruby Language. Ruby-on-Rails has attracted so much attention because of the plethora of development tools it provides as well as the extreme ease in the creation of a CRUD web application through a mechanism it calls scaffolding. It has at least one excellent textbook and many IDEs (including NetBeans) provide support for it.

Web frameworks and CMSs using Php are numerous. Our choice is the Zend Framework whose home page is:
http://framework.zend.com/
Here are some other choices: Akelos, CakePHP, CodeIgniter, Drupal, FUSE, Horde, Joomla, Kohana, LISA, Midgard, Orinoco, Php on Trax, Qcodo, SilverStripe/Sapphire, Symfony, Zoop. A good site to find general information and comparisons of these is:
Wikipedia Web Framework Comparison

Installation

Apache Rewrite Module

Apache's Rewrite module is needed for essentially the same reasons as mentioned in the Php/Apache Authentication document; it is used to force most URLs through a front controller. See that document for details.

Zend Framework

The distribution, available either as a zip or tar-gzipped archive, is available either a full distribution or a minimal form:
ZendFramework-1.9.2-minimal.zip
The "minimal" distribution, is all you really need. The other version, a much larger package, provides documentation and examples. In either case the crucial installation folder is the library subfolder.
    Windows   Linux    

Windows

Assuming we're using the "minimal" distribution, the required folder is:
ZendFramework-1.9.2-minimal\library
Move and rename this folder to the following (or to a location of your choosing):
C:\ZendLibrary

Generator / HelloWorld

The other useful piece of software is a tool to generate a directory/file structure which suffices to create a "hello world" application which can be modified and augmented. Such a generator exists in other web applications but, for whatever reason, is not present here. The generator we will use is a relatively primitive GUI application written in Java. You need to download this Java application archive:
MakeZFProject.zip
Install this as a Java Project from Existing Sources. You can run it within NetBeans (the easiest way), or create a standalone Java GUI application.

Create ZendHello via the project generator

Create the Zend Framework "Hello World" application by running the MakeZFProject application. You are presented with the following GUI form:
Fill in the fields like this (let the Browse button help you if so desired): After filling in the fields, create the project by clicking the Create Zend Framework Project button. A report of files created is presented in a popup dialog.

Upon activating the button, the MakeZFProject application holds in persistent memory the first three fields (in the file .mkzf-properties in your home directory). Subsequent activations of MakeZFProject will not overwrite any existing file; this can be tested by activating a second time with the same information.

Create ZendHello via download/modify

Alternatively, you can download the ZendHello project from download the ZendHello.zip archive, extract it into the desired location and modify to suit your installation:
public/.htaccess     reset RewriteBase if necessary
public/index.php     replace '/usr/local/share/ZendLibrary' if necessary,

Execute it

Assuming the /default Base URL is used, you can now run the project by activating the URL:
http://localhost/default/ZendHello
If you want to use NetBeans as the project editor, create a new Php Project from Existing Sources as is done in other Php projects.

Framework Generator Description

The structure of the ZendHello project created by our MakeZFProject application creates the following file/folder structure beneath the Base Folder:
ZendHello/
  index.php                        forwards to public/
  library/
  public/
    .htaccess                      funnel URLs to front controller
    index.php                      front controller
    images/
    js/
    css/
  application/
    config.ini                     database configuration
    controllers/
      IndexController.php          controller for "/index"
    models/
    views/
      filters/
      helpers/
      layouts/
        layout.phtml               layout template
      scripts/
        index/
          index.phtml              view for "/index/index"
The initial appearance is somewhat bewildering with so many files and folders needed to create a simple "hello world" project. The MakeZFProject application permits you to modify each of the seven files created by selecting the file through the Edit menu. Here are the file contents:

Initial Redirection

This causes redirection to the public folder.

index.php
<? header("location: public"); ?>
Technically, we want to permit public web access only to this folder. Making index.php do this redirection does not guarantee that other folders can be accessed, but we will ignore this problem during development.

Rewrite activation of front controller

Assuming that you've set the Base URL to "/default", the file which sends everything through the front controller is this:

public/.htaccess
RewriteEngine on RewriteBase /~rkline/ZendHello/public RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^.*$ index.php
Read this as follows
if the requested URL is not a file, then
apply the RewriteRule, sending it to the "front controller," index.php (in the same public folder).
In particular,

A "final" presentation

If we intend to use this web application in production (not really this one in particular, but some other Zend Framework application), then we need to make the public directory the web application's root. To do so, we should
  1. Remove or rename the .htaccess file. In general, the usage of an .htaccess file is less efficient than an Apache configuration specifications in one of its ".conf" files. In addition, .htaccess directly conflicts with a variation that we need to create.
  2. Create the following Apache-specific content (adjust the details as necessary), either in a new dedicated configuration file (Ubuntu), or appended to the httpd.conf configuration file (Windows):
    Alias /zendhello "THE-PATH-TO/ZendHello/public"
    
    <Directory "THE-PATH-TO/ZendHello/public">
      Options IncludesNoExec
      AllowOverride None
    
      Order allow,deny
      Allow from all
    
      RewriteEngine on
      RewriteBase /zendhello
      RewriteCond %{REQUEST_FILENAME} !-f
      RewriteRule ^.*$ index.php
    </Directory>
    
After doing so, the application is to be run as the URL: http://localhost/zendhello/

Setup features

The front controller does the basic setup for each non-file URL.

public/index.php
<?php $rootDir = dirname(dirname(__FILE__)); set_include_path( get_include_path() . PATH_SEPARATOR . '../library' . PATH_SEPARATOR . '/usr/local/share/ZendLibrary' . PATH_SEPARATOR . '../application/models/' ); include 'Zend/Loader/Autoloader.php'; $autoloader = Zend_Loader_Autoloader::getInstance(); //automatically load classes of the form "My_" $autoloader->registerNamespace("My_"); $registry = Zend_Registry::getInstance(); $registry->set('rootDir', $rootDir); // Load configuration $config = new Zend_Config_Ini('../application/config.ini', 'general'); $registry->set('config', $config); $db = Zend_Db::factory($config->db); $registry->set('db', $db); Zend_Db_Table::setDefaultAdapter($db); date_default_timezone_set($config->date_default_timezone); // setup front controller $frontController = Zend_Controller_Front::getInstance(); $frontController->throwExceptions(true); $frontController->setControllerDirectory('../application/controllers'); // setup the layout Zend_Layout::startMvc(array('layoutPath' => '../application/views/layouts')); // run $frontController->dispatch();
The config.ini file is the place for all the applications run-time configuration information. For the most part, we want to use this to specify the database. Initially we provide only enough so that the setup Zend_Db usages in the front controller will "go through."

application/config.ini
[general] db.adapter = PDO_MYSQL db.params.host = db.params.dbname = db.params.username = db.params.password = date_default_timezone = "America/New_York"

The controller/action activation

The Zend Framework, like many others, create URLs by adding two components to the base:
http://... BASE .../controller/action
The controller part corresponds programatically to a Php class within the applications/controllers directory. The action part corresponds to a member function within that class. The entire pair controller/action is mapped, by default, to a corresponding view script (see below).

Separate controllers are thought to make separations between distinct "portions" of the web applications and actions create the behaviors within these separate portions.

The entry URL immediately redirects us to
http://localhost/default/ZendHello/public/
In the terms of the framework logic, this defaults to calling the index controller:
http://localhost/default/ZendHello/public/index
The index controller, by default, calls the index action:
http://localhost/default/ZendHello/public/index/index
The controller/action creates an instance of the IndexController class, calls the indexAction function and combines these effects with the "index view" below. Data can be created and passed from the controller to the view script through the view member object.

application/controllers/IndexController.php
<?php class IndexController extends Zend_Controller_Action { public function init() { //called before any action } public function indexAction() { $this->view->pageTitle = "Hello World"; } }

Layout template

The template file layout.phtml is used, by default, for all application URLs. The statement:
Zend_Layout::startMvc(array('layoutPath' => '../application/views/layouts'));
used in the front controller which makes this possible. The view content is simply dumped into the body. Additionally, the headLink and headScript operations establish "places" for stylesheet links and script files to be added by the specific controller or view script.

application/views/layouts/layout.phtml
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html;charset=utf-8" /> <title><?= $this->escape($this->pageTitle) ?></title> <?= $this->headLink() ?> <?= $this->headScript() ?> </head> <body> <div id="content"> <?= $this->layout()->content ?> </div> </body> </html>

View for "index" URL

A controller/action pair, by default, finds its associated view script as
application/views/scripts/contoller/action.phtml
This, therefore, is the default script used by the index/index controller/action pair.

application/views/scripts/index/index.phtml
<h2><?= $this->pageTitle ?></h2>


© Robert M. Kline