CONTENTS INCLUDE:
n
n
Introducing The Zend Framework
Introducing The MVC Design Pattern
Framework Prerequisites
Getting Started with
the Zend Framework
n
Installing The Zend Framework
n
Creating Your First Project
n
Sending Variables to the View and more...
By W. Jason Gilmore
The Zend Framework (http://framework.zend.com) is an open The Zend Framework uses object-oriented features only
source object-oriented Web framework which significantly available within PHP 5, with the latest release supporting PHP
reduces the barriers typically encountered when creating 5.2.4 and newer. To take advantage of features such as
powerful Web applications. It does so by providing developers custom routing you’ll need to implement Apache’s
with an array of tools which facilitate many of the most mod_rewrite module. Finally, you may need to enable specific
commonplace yet tedious tasks, such as data validation, PHP extensions in order to take advantage of specific Zend
database access and manipulation, sending e-mail, user Framework components. Consult the Zend Framework
account management, search engine optimization, and documentation for a list of extension dependencies.
internationalization.
INSTALLING THE ZEND FRAMEWORK
The Zend Framework developers also place special emphasis
on “the latest Web 2.0 features”, offering simple solutions for
You can download the Zend Framework from the following
AJAX integration, content syndication, and communication
location: http://framework.zend.com/download/latest
with popular APIs such as those offered by Amazon.com,
Google, and Yahoo!. On this page you’ll find several packages, with accompanying
www.dzone.com
include_path = ".:/php/includes"
If you’re unable to modify the php.ini file, then you can set the
include_path directive within an .htaccess file like this:
Getting Started with the Zend Framework
Figure 1: The MVC pattern isolates application components
With Zend_Tool installed, you can create your first Zend Creating a View
Framework-powered project in mere seconds. To create a Each action is accompanied by a view, which contains the
project, open a command prompt and navigate to the location HTML used to render the page associated with the action.
where you’d like the project directory to reside. Then execute For instance, the view associated with the About controller’s
the following command, replacing PROJECT_NAME with the contact action would be named contact.phtml, and would
name of your particular project: reside in the following directory:
%>zf create project PROJECT_NAME
application/views/scripts/about/
In addition to creating the directory structure and files
necessary to power a Zend Framework-driven Website, Zend_Tool does not support the creation of view skeletons,
this command will also create an index controller and likely because it’s probably more efficient to simply create
corresponding view which will represent the home page. them using an IDE in the first place. However if you’ve already
You can confirm that the project was created successfully by used Zend_Tool to create the corresponding action, then the
navigating to the site’s home page from within your browser, default behavior is to create an associated view. See the Zend_
but first you’ll need to set your Web server’s document root Tool documentation for more information.
to the project’s public directory (this directory is found in the
project’s root directory, and is autogenerated by Zend_Tool). Creating a Template
This is because all requests are funneled through the project’s By default any rendered view will comprise the whole of
front controller, which is responsible for processing the request the Web page displayed within the browser. Because you’ll
and returning the response. You don’t have to create the probably want to wrap a template around the views which
front controller, it’s automatically created when you create a contains elements such as a header and footer. Configure
new project using Zend_Tool. Once the document root is set, your application to recognize the template by opening the
restart your Web server and navigate to the site’s home page, application/configs/application.ini file and adding the
and you’ll see the welcome message displayed in Figure 2. following lines:
application/
configs/ VIEW HELPERS
application.ini
controllers/
ErrorController.php Within your views you’ll often need to repeatedly manipulate
IndexController.php data in a specific way. For instance, if you were creating a
models/
views/
weight loss application, then you’ll regularly want to refer to a
helpers/ user according to gender, such as:
layouts/
He has lost 4.25 lbs this week.
layout.phtml
scripts/
error/ Because the user could be male or female, you’ll need a way
error.phtml to dynamically change the string to use He or She, accordingly.
index/
index.phtml Such decision making will likely occur throughout your
Bootstrap.php application, therefore rather than repeatedly use if or ternary
library/
public/
statements, you can create a view helper and use it like this:
.htaccess
index.php <?= $this->Gender($user); ?> has lost 4.25 lbs. this week.
tests/
This Gender view helper is defined next:
Let’s take a moment to examine those directories and files
class My_View_Helper_Gender extends
which haven’t already been introduced. Zend_View_Helper_Abstract
{
The configs directory contains the application’s configuration public function Gender($user)
{
file, application.ini. This file is introduced in the later section
return $user->Gender == "m" ? "he" : "she";
“The Configuration File”. }
}
The ErrorController.php file is automatically created when
Save this helper to a file named Gender.php and store it within
creating a project using Zend_Tool. It handles any errors of
the application/views/helpers directory.
codes such as 404 and 500 which are generated when using the
application.
THE CONFIGURATION FILE
The views/helpers directory contains the application’s view
helpers. This feature is introduced in the later section “View The Zend Framework makes it easy to centrally manage your
Helpers.” application’s configuration data such as database connection
parameters, Web service API keys, and e-mail addresses.
The Bootstrap.php file is responsible for initializing the Although it’s possible to manage this information from
resources used by your application. data sources such as a database, the most commonplace
solution is via the default application.ini file, located within
The public directory contains files which are directly accessible the application’s configs directory. The file is organized using
by the user, such as the application’s images, javascript files, the common INI format used by many applications, with each
and CSS. You’re free to organize these files within the public configuration variable assignment performed like this:
directory as you see fit, however I prefer to simply place
them within directories named images, javascript, and css, email.support = "support@example.com"
respectively. The public directory also contains an .htaccess Recognizing the need to often adjust configuration data based
file, which is responsible for rewriting all incoming requests on the phase of development (development, testing, staging,
(save for anything stored in the public directory) to the index. and production are commonplace phase monikers), this file is
php file, which is the application’s front controller. broken into four sections, with each representing a phase, like
so:
The tests directory contains any PHPUnit tests you’ve created
to test your application [production]
phpSettings.display_startup_errors = 0
email.support = "support@example.com"
SENDING VARIABLES TO THE VIEW
[staging : production]
phpSettings.display_startup_errors = 1
Because much of the data found in the application views will
[testing : production]
likely be dynamically generated, you’ll need to regularly pass phpSettings.display_startup_errors = 1
variables from actions to views. Known as instance properties,
[development : production]
these variables are assigned within the action like this, where email.support = "admin@example.com"
NAME is the name of your variable: phpSettings.display_startup_errors = 1
/account/confirm/key/7dugpl97812fjkl
Because your actions will often call upon the same code to
carry out certain tasks, such as accessing the configuration file You can then access the key parameter from within the confirm
as demonstrated in the previous example, it makes sense to action like this:
consolidate that code within a single location. You can do this
using a special init() method, typically placed at the top of a $key = $this->_request->getParam('key');
controller class. Within this method you can place for instance
But what if you wanted to construct a URL which flouted this
the code used to retrieve the configuration data:
convention? For instance, you might want to string together
parameters sans their keys in order to create a more compact
public function init()
{ URL which looks like this:
$bootstrap = $this->getInvokeArg('bootstrap');
$configArray = $bootstrap->getOptions();
/tutorials/php/zend_framework/
$this->config = new Zend_Config($configArray);
}
You can perform such tasks easily using custom routes. For
Notice the subtle difference between the snippet used to instance, to retrieve the php and zend framework parameters,
retrieve the configuration variables and the previous snippet passing them to the tutorials controller’s index action, define
shown in the previous section. When creating variables which the following custom route:
will be accessed throughout the controller, you’ll need to make
$route = new Zend_Controller_Router_Route(
them instance properties via $this. '/tutorials/:parent_category/:child_category',
array(
'controller' => 'tutorials',
CUSTOM ROUTING 'action' => 'categories'
)
);
$router->addRoute('confirm-account', $route);
Although the Zend Framework’s default routing behavior is
to deconstruct the URL path, identifying the controller and You can then access the values represented by the :parent_
action by the order of URL segments (for instance /about/ category and :child_category placeholders using the following
contact/ maps to the About controller’s contact method, syntax:
you’ll inevitably want to override this default behavior and
create your own custom routes. To do this you’ll invoke the $parent = $this->_request->getParam('parent_category');
$child = $this->_request->getParam('child_category');
Zend_Controller_Router_Route() class, passing along the
URL pattern, and destination controller and action. These
custom routes are defined within a method typically named
FORMS PROCESSING
_initRouter() (I say typically because this particular name is
optional although usual) found in the Bootstrap.php file. For
instance to override the destination of the /about/contact URL In the previous section you learned how to access URL
path, instead invoking the Help controller’s support method, parameters using the $this->_request->getParam() method.
you would add the following method to your Accessing data passed via a Web form is similarly trivial using
Bootstrap.php file: the $this->_request->getPost() method. For instance, if a
DZone, Inc.
DZone, Inc. || www.dzone.com
www.dzone.com
5
Getting Started with the Zend Framework
form’s text field is assigned the name email, then this value can
be accessed via the form’s action destination in the following TALKING TO THE DATABASE
fashion:
DZone, Inc.
DZone, Inc. || www.dzone.com
www.dzone.com
6
Getting Started with the Zend Framework
extends the framework’s Zend_Db_Table_Abstract class in in a particular country, you’ll need to define the relationship
order to be endowed with Zend_Db’s special features: within both models. Within the member name you’ll define the
dependency like this:
class Model_Country extends Zend_Db_Table_Abstract {
protected $_name = 'country'; protected $_referenceMap = array (
} 'Country' => array (
'columns' => array('country_id'),
'refTableClass' => 'Model_Country'
The $_name attribute can be used to override Zend_Db’s
)
presumption that the model and corresponding table name are );
identical. For instance if the table name is actually countries
but you preferred to use singular form for model names, then Within the country model you’ll define the associated
$_name can be used to rectify this discrepancy. relationship like this:
BUY NOW
books.dzone.com/books/zendframework
#82
CONTENTS INCLUDE:
■
About Cloud Computing
Usage Scenarios Getting Started with
n
Aldo
■
Cloud#64Computing
■
Underlying Concepts
Cost
by...
■
Upcoming Refcardz
youTechnologies ®
Data
■
t toTier
brough Comply.
borate.
Platform Management and more...
■
Chan
ge. Colla By Daniel Rubio
tion:
dz. com
tegra ternvasll
ABOUT CLOUD COMPUTING one time events. TEN TS
INC ■
HTML LUD E:
us Ind Anti-PPaat
Basics
Automated growthHTM
ref car
nuorn
■
Valid
ation one time events, cloud ML
connected to what is now deemed the ‘cloud’. Having the capability to support
ul M.
computing platforms alsoulfacilitate
4 Open the gradual growth curves
n an
Page Source
o
■
s
Vis it
C
faced by web applications. Tools
Core
By Key ■
Elem
atte
has changed substantially in recent years, especially with Structur
E: al Elem ents
INC LUD gration
NTS
P the entrance of service providers like Amazon, Google and Large scale growth scenarios involvingents
specialized
and mor equipment
rdz !
HTML
CO NTE Microsoft. es e... away by
(e.g. load balancers and clusters) are all but abstracted
Continu at Every e chang
m
About ns to isolat
relying on a cloud computing platform’s technology.
Software i-patter
space
Adobe Catalyst
rdz .co
■
n
Re fca
e Work
Build
riptio
and Ant These companies
Desc have a Privat
are in long deployed trol repos
itory web applicationsge HTM
L BAS
■
to mana
Patterns Control
■
that adaptDeve
lop softw
and scale to
n-con
large user
a versio bases,ng and making them In addition, several cloud computing ICSplatforms support data
les to ize mergi
ment
rn
Version e... Patte it all fi minim le
tier technologiesHTM
Manage s and mor e Work knowledgeable in amany
ine to
mainl aspects related tos multip
cloud computing. that Lexceed the precedent set by Relational
space Comm and XHT
■
ref ca
Build
re
OUS
Flash Builder 4
chang
ding code Level
as the desc
the ima alt attribute ribes whe
www.dzone.com
a Task
ive data pt. Server-s
ce
NTINU of buil tr what it is a cloud computing es as platform can offer your ut web output e in clien ment.
T CO cess ion con it chang e witho likew ide lang t-sid e ge is describe re the ima
ise use mec hanism. fromAND
e name CLOUD COMPUTING PLATFORMS
the pro ject’s vers applications. and subm sourc
ABOU (CI) is
with uniqu are from web
The eme pages and uages like Nested
unavaila s alte ge file
rd z!
Maven 3
reposit ed via particul tions that e Pay only what you consume
tagge or Amazon’s cloud you cho platform
computing
the curr isome
heavily basedmoron fine. b></ ed insid
anti e imp a></
For each (e.g. WAR
ent stan ose to writ
lain the t
es more e
not lega each othe
and x” solu b> is
be exp text) to “fi duc Web application deployment ge until
nden a few years
t librari agonmen was similar app ortant,
ns are to pro packa t enviro industry standard
that will softwaredardand virtualization
e HTM technology.
Mo re
DZone, Inc.
ISBN-13: 978-1-934238-84-4
140 Preston Executive Dr. ISBN-10: 1-934238-84-8
Suite 100
50795
Cary, NC 27513