Zend Framework: Fundamentals

fishhookFladgeInternet και Εφαρμογές Web

13 Δεκ 2013 (πριν από 3 χρόνια και 5 μήνες)

320 εμφανίσεις


© 2006-2009 Zend Technologies, Inc. All rights reserved.















































Zend Framework:
Fundamentals


Participant Guide
Table of Contents


COURSE INTRODUCTION i

Zend Framework: Fundamentals Course ...................................................................... i
About Zend ........................................................................................................................ i
1: INTRODUCTION TO ZEND FRAMEWORK 1
Course Goals and Approach ........................................................................................ 2
Course Projects ................................................................................................................. 4
PHP Collaboration Project .............................................................................................. 7
Goals of Zend Framework .............................................................................................. 8
Framework License .......................................................................................................... 9
What's in Zend Framework ............................................................................................ 10
2: RAPID APPLICATION DESIGN 11
Steps to RAD ................................................................................................................... 14
RAD Exercise ................................................................................................................... 16
3: MVC DESIGN PATTERN 52
MVC Elements and Structure ....................................................................................... 54
MCV Mapped to the Web ........................................................................................... 61

GUEST BOOK INTRODUCTION 66

4: ZEND FRAMEWORK CONTROLLER RELATED COMPONENTS (GB) 133
Zend_Controller .............................................................................................................. 67
Bootstrap Architecture .................................................................................................. 75
Controller Execution Methods ..................................................................................... 86
5: ZEND FRAMEWORK GENERAL COMPONENTS (GB) 92
Zend_Config ................................................................................................................... 94
Zend_Exception ............................................................................................................ 109
Zend_Session ................................................................................................................. 113




6: ZEND FRAMEWORK MODEL RELATED COMPONENTS (GB) 122
Zend_Db ........................................................................................................................ 132
Zend_Db_Profiler .......................................................................................................... 138
Zend_Db_Table ............................................................................................................ 143
Zend_Db_Select ........................................................................................................... 162
Zend_Form ..................................................................................................................... 170


7: ZEND FRAMEWORK VIEW RELATED COMPONENTS (GB) 191
Zend Framework and Views ....................................................................................... 192
Zend_View..................................................................................................................... 195
View Scripts ................................................................................................................... 196
Zend_Layout ................................................................................................................. 208

Wiki EXERCISE INTRODUCTION 218

8: MORE CONTROLLER RELATED COMPONENTS (WIKI) 221
Front Controller Plugins ................................................................................................ 224
Action Helpers .............................................................................................................. 228
9: MORE GENERAL COMPONENTS 234
Zend_Registry ................................................................................................................ 237
Zend_Log ....................................................................................................................... 243
10: MORE MODEL RELATED COMPONENTS 253
Authorization and Authentication ............................................................................ 257
Zend_Acl ....................................................................................................................... 261
Zend _Auth .................................................................................................................... 270
Zend_Filter ..................................................................................................................... 282
Zend_Validate .............................................................................................................. 288
Zend_Filter_Input .......................................................................................................... 292
11: MORE VIEW RELATED COMPONENTS 294
Zend_View_Helper ....................................................................................................... 297
Placeholders and Partials ........................................................................................... 312
Plugins ............................................................................................................................ 317
Wiki Coding Exercise ................................................................................................... 324
Supporting Documentation ....................................................................................... 326




Introduction

ZEND FRAMEWORK: FUNDAMENTALS
The Zend Framework: Fundamentals course is designed for experienced PHP programmers who
want to learn to combine ZF concepts and structural elements to utilize the full power of this
development kit for PHP 5 applications. Zend Framework is an open-source class library with a
central theme of “extreme simplicity”. ZF helps you to reduce the tedious details of coding
and instead allows developers to be more productive as they focus on the big picture. Utilizing
a collection of customizable PHP classes, ZF provides robust functionality suitable for both
large and small tasks.
This course combines teaching ZF with the introduction of the Model-View-Component (MVC)
design pattern, to ensure you learn current best practices in PHP development. The Zend
Framework course helps you to learn by doing. Each discussion of related components is
presented with examples of how best to utilize them in your applications, along with relevant
exercises and projects to reinforce concepts learned.

ZEND FRAMEWORK (ZF): EXTENSIBILITY & PRODUCTIVITY
In designing this development kit, the development team aimed to provide the most commonly
required 80% of the value you need, skipping the other more complicated 20% in order to make
it simple and quick to use. By focusing on the most commonly needed functionality, we
dramatically lower the learning curve and your training costs. We support you in your
customization efforts via:
 Extensible and well-tested base code to extend and augment
 A ‘use-at-will’ architecture so you get what you need without being locked-in
 No configuration files necessary to get up and running, or when maintaining and
deploying your apps

About Zend
Zend is the PHP company. Businesses utilizing PHP know Zend as the place to go for PHP
expertise and sound technology solutions. Zend delivers premier web application platform
products and services for PHP applications. With commercial products and services that enable
developers and IT personnel to deliver business-critical PHP applications, Zend is taking the
power of PHP to the enterprise.



Zend provides a suite of products that supports the entire PHP lifecycle, from development to
production, of your business-critical PHP applications. Often, PHP programmers work in
demanding environments, where they are called upon to fulfill more than one role. Zend
products allow those who work in web application development - as well as related fields like
system administration - to seamlessly utilize all their relevant features to rapidly produce a
dynamic, robust web application in a stable, reliable environment.

Zend Platform
Setting the Standard in PHP Application Performance & Availability
Zend Platform is the all-in-one production environment that ensures your PHP applications are
available, fast, reliable and scalable. It uniquely guarantees application uptime and reliability
through enhanced PHP monitoring and immediate problem resolution.

Zend Studio for Eclipse
The Proven PHP Development Environment
Zend Studio is the leading PHP Integrated Development Environment (IDE) designed for
professional developers, which includes all the development components necessary for the full
PHP application lifecycle.

Zend Guard
Protect your Code and IP
Zend Guard provides independent software vendors and IT managers with the ability to safely
distribute and manage the distribution of their PHP applications while protecting their source
code.

Zend Optimizer
Optimize your PHP code
Zend Optimizer is a free application that runs files encoded using Zend Guard and enhances the
overall performance of your PHP applications.

Zend Core
Save Time with Certified Versions of PHP
Zend Core is a Zend certified and supported version of the open source PHP. It uniquely
delivers a seamless out-of-the-box experience by bundling all the necessary drivers and third
party libraries to work with the database of your choice.

Zend Engine
The Heart of PHP
At the center of PHP is the Zend Engine, the component that parses and executes PHP files. It
is open source software and available under an Apache-style license.
Slide 1

Copyright © 2006-2009, Zend Technologies Inc.
ZEND FRAMEWORK:
FUNDAMENTALS


Participant Guide | ZF Fundamentals
1
© 2006-2009 Zend Technologies, Inc.
Slide 2

Copyright © 2006-2009, Zend Technologies Inc.
| 2
Course Goals
• In this course, we will study Zend Framework (ZF) so you will understand…

the concept behind the framework

the structural elements that make up the framework

the power of combining these elements for a complete design solution


ZF Fundamentals | Participant Guide
© 2006-2009 Zend Technologies, Inc.
2
Slide 3


Copyright © 2006-2009, Zend Technologies Inc.
Course Approach
• The course approach will be guided learning, with more and more of the coding
to be completed by you
• The key emphasis is not on what Zend Framework is, but how to apply it when
building applications
• Topics will be addressed at the beginner-level user, leading to an intermediate-
level … an Advanced ZF course will cover many of these topics in more depth,
as well as introduce new ones
• Topic Sequence

Rapid Application Design

The MVC design pattern

How to build and work with each section: Controller – View – Model, along
with the Zend Framework components that apply to each layer
| 3


Participant Guide | ZF Fundamentals
3
© 2006-2009 Zend Technologies, Inc.
Slide 4

Copyright © 2006-2009, Zend Technologies Inc.
Course Projects
• In order to give you practical application in using ZF for application
development, we will work with 3 Training Projects (building in complexity):
• A "Hello, World" application - your first project
• A Guest Book application - your practice project
• A Wiki application - your final, reinforcement project
• Your first steps will be to complete a working web application using ZF's Rapid
Application Design

You can do this without fully understanding either Zend Framework or the
Model-View-Controller design pattern!
| 4


ZF Fundamentals | Participant Guide
© 2006-2009 Zend Technologies, Inc.
4
Slide 5

Copyright © 2006-2009, Zend Technologies Inc.
Course Projects
• Next, we work with a relatively simple but useful Guest Book application

We will look at each "layer" of the MVC pattern, and the corresponding ZF
components as they appear within the application
• Finally, we examine a more complex application, a Wiki, and learn about some
important additional ZF components
• Why 3 projects? Because each builds in complexity and gives you practice in
applying what you are learning, in chunks of information, building upon what
you already know… here's an analogy…
| 5
Bread and Butter
Bread, Butter
Turkey Sandwich
Bread, Butter, Turkey, Lettuce
Turkey Club Sandwich
Bread, Butter, Turkey, Lettuce,
Bacon, Tomato, 3-layers


Participant Guide | ZF Fundamentals
5
© 2006-2009 Zend Technologies, Inc.
Slide 6

Copyright © 2006-2009, Zend Technologies Inc.Copyright © 2006-2009, Zend Technologies Inc.
MOD 1: INTRODUCTION TO ZEND FRAMEWORK


ZF Fundamentals | Participant Guide
© 2006-2009 Zend Technologies, Inc.
6
Slide 7

Copyright © 2006-2009, Zend Technologies Inc.
| 7
The PHP Collaboration Project
SOA,
Web Services,
etc.
Open
Source
Community
PHP
Language
Zend Studio
for Eclipse
Zend
DevZone
Zend PHP
Framework
Zend Framework is a
critical component of the
overall vision for PHP in
the Enterprise


Participant Guide | ZF Fundamentals
7
© 2006-2009 Zend Technologies, Inc.
Slide 8

Copyright © 2006-2009, Zend Technologies Inc.
| 8
Goals of Zend Framework
• Zend Framework strives to be fundamentally…

an industry-leading framework for PHP application development

a partnership among many companies already experienced in PHP
Framework development (Google, Adobe, Microsoft, and others)
• Zend Framework strives to be technically…

a source of high-quality, PHP 5 / E_STRICT compatible application
components

completely PHP 5 powered

modular in design, allowing developers to use ZF components at will, and
the framework as they see fit



Keep PHP competitive with other technologies

.NET, Java, etc.


Provide “clean” IP to enable commercial use

Real companies can’t just “borrow” code from the Internet without clear licensing


Exploit the power of PHP 5 to its full advantage


ZF emulates some of the other PHP technologies (for example, PEAR) in striving for simplicity, which
has always been PHP’s overall goal


The underlying technologies may be extremely complex, but the interface - the ZF components - is
designed for ease of use


‘Use-At-Will’ Architecture

Utilize individual components (controller/model) without being forced to use everything


No Configuration Necessary

We leave configuration up to the developer's discretion


Based on the Pareto Principle - 80/20 Rule

Works for the most common use cases out of the box- built for extensibility
ZF Fundamentals | Participant Guide
© 2006-2009 Zend Technologies, Inc.
8
Slide 9

Copyright © 2006-2009, Zend Technologies Inc.
| 9
The Framework License
• Zend Framework is licensed using the BSD license

Anyone can use it, for anything, no strings attached – period

Business friendly
• Along with the license of the framework itself, contributors must sign a
Contributor License Agreement (CLA)

Protects the IP of the Framework for all contributors and users

Based on the Apache Software Foundation CLA



Unlike some other licenses (GPL), a BSD license does not require that you make your application
open source

People can download and use it without any IP risks


The CLA process assures that the code is free of legal issues - good for businesses

All contributors must sign this (idea borrowed from Apache Software Foundation project)

There are no copyright or patent claims on any part of ZF

Does not give Zend any proprietary rights on your code - only a license to use your code…

you can take your own code and continue to develop, use or apply it

Participant Guide | ZF Fundamentals
9
© 2006-2009 Zend Technologies, Inc.
Slide 10

Copyright © 2006-2009, Zend Technologies Inc.
| 10
What’s in Zend Framework?
Simple
,
convenient
,
object-oriented
solutions to
common web
application
development
tasks
,
including
:



ZF is both a Full-Stack Framework and a Component Library


It is fully object-oriented


The Component library is 100% PHP


There is extensive supporting documentation, with over 500 examples

ZF Fundamentals | Participant Guide
© 2006-2009 Zend Technologies, Inc.
10
Slide 11

MOD 2: RAD (Rapid Application Development)


Participant Guide | ZF Fundamentals
11
© 2006-2009 Zend Technologies, Inc.
Slide 12

Copyright © 2006-2009, Zend Technologies Inc.
| 12
Off to an Easier Start using RAD...
• Zend Framework provides a set of components that allow you to rapidly
develop the basic structure of a web application,
Zend_Tool
&
Zend_Application
• Zend_Tool provides an easy way to create the skeleton (directory structure
and essential components) for a Zend Framework-based web application,
greatly reducing the time you spend to get your applications up and running
• Zend_Application provides a bootstrapping facility for applications, with
reusable resources, common- and module-based bootstrap classes and
dependency checking. It also takes care of setting up the PHP environment
and introduces autoloading by default
• In this beginner-level course, we will take a "black box" approach as you learn
how to use these components to create PHP applications


ZF Fundamentals | Participant Guide
© 2006-2009 Zend Technologies, Inc.
12
Slide 13

Copyright © 2006-2009, Zend Technologies Inc.
| 13
Generic File System Layout for MVC in ZF
• Zend Framework applications are built
using the MVC design
• When you create a project using the ZF
Rapid Application Design functionality,
ZF will automatically generate a basic
site structure within the designated
directory, and supply initial controllers
and views (
shown at right
)
application/
…..Bootstrap.php
…..configs
……….application.ini
…..controllers/
……….ErrorController.php
……….IndexController.php
…..models/
…..views/
……….helpers
……….scripts/
……………error/
………………..error.phtml
.……….index/
………………..index.phtml
library/
public/
……….index.php
tests/
…..application/
……….bootstrap.php
…..library/
……….bootstrap.php
phpunit.xml



Note that ZF automatically creates the directory structure

Participant Guide | ZF Fundamentals
13
© 2006-2009 Zend Technologies, Inc.
Slide 14

Copyright © 2006-2009, Zend Technologies Inc.
| 14
Steps to RAD: Phase 1
1.Download and Install Zend Framework (if you haven't already)
2.Set the Project Path (set doc root…)
3.Create the Project
4.Make sure the ZF Library is either recursively copied or symlinked to the
project's library/ directory
5.Check (edit) the Bootstrap
6.Configure the Application (adjust settings for PHP environment)
7.Add Controllers beyond those created by default
8.Add/edit View Scripts
… You are able to generate a Welcome Page at this point



Summary of basic steps a developer should take to implement the easy-to-use RAD feature of ZF


ZF Fundamentals | Participant Guide
© 2006-2009 Zend Technologies, Inc.
14
Slide 15

Copyright © 2006-2009, Zend Technologies Inc.
| 15
Steps to RAD: Phase 2
9.Create a Layout
… You can see the xhtml header, head, title,
and body sections
10.Create a Model and database table
… You can see the rudimentary Guestbook
11.Create a Form
… It's not Web-worthy, but it's functional!
Congratulations!!


Participant Guide | ZF Fundamentals
15
© 2006-2009 Zend Technologies, Inc.
Slide 16

Copyright © 2006-2009, Zend Technologies Inc.
| 16

We will now follow these relatively simple steps to create your first ZF
project… "Hello, World!"

As we work through each step of the RAD process, we will look at the
resulting code that has been created

You will see how little editing is required to create a viable project, as ZF
produces the entire project structure for you, according to the MVC design
pattern
Exercise:RAD Implementation
Hello, World!


ZF Fundamentals | Participant Guide
© 2006-2009 Zend Technologies, Inc.
16
Slide 17

RAD: Phase 1


Participant Guide | ZF Fundamentals
17
© 2006-2009 Zend Technologies, Inc.
Slide 18

Copyright © 2006-2009, Zend Technologies Inc.
1.Download and install Zend Framework (if you haven't already)
2.Set the project path (set doc root…)
3.Create the Project
4.Make sure the ZF library is either recursively copied or symlinked to the
project's library/ directory
5.Check (edit) the Bootstrap
6.Configure the Application (adjust settings for PHP environment)
7.Add Controllers beyond those created by default
8.Add/edit View Scripts
… You should be able to generate a Welcome Page at this point
| 18
Steps to RAD: Phase 1


ZF Fundamentals | Participant Guide
© 2006-2009 Zend Technologies, Inc.
18
Slide 19

Copyright © 2006-2009, Zend Technologies Inc.
| 19
Installing Zend Framework

http://framework.zend.com/download/latest

Installing the framework is quite simple - just modify your include_path to
include the library/ directory
From php.ini:
From .htaccess
Hello, World!



Two of the ways to add ZF to your include path…


Of course, ZF may also be added to your include path via PHP code

Participant Guide | ZF Fundamentals
19
© 2006-2009 Zend Technologies, Inc.
Slide 20

Copyright © 2006-2009, Zend Technologies Inc.
1.Download and install Zend Framework (if you haven't already)
2.Set the project path
3.Create the Project
4.Make sure the ZF Library is either recursively copied or symlinked to the
project's library/ directory
5.Check (edit) the Bootstrap
6.Configure the Application (adjust settings for PHP environment)
7.Add Controllers beyond those created by default
8.Add/edit View Scripts
… You should be able to generate a Welcome Page at this point
| 20
Steps to RAD: Phase 1


ZF Fundamentals | Participant Guide
© 2006-2009 Zend Technologies, Inc.
20
Slide 21

Copyright © 2006-2009, Zend Technologies Inc.
| 21
Locate the ZF Utility (Create Alias)
NOTE: If you are using Studio, you do not have to run these steps because of
Studio's built-in support for ZF… If using a different IDE, this will make things
easier
• There is a /bin subdirectory within the ZF installation
• This /bin directory contains the scripts zf.sh (Unix) and zf.bat
(Windows)
• Include this subdirectory in your system's path setting
or
Create an alias in your shell alias zf=/path/to/bin/zf.sh[bat]
or
Use pear.sfcampus.org PEAR channel
Hello, World!



Creating an alias for the full path will save time in coding

Participant Guide | ZF Fundamentals
21
© 2006-2009 Zend Technologies, Inc.
Slide 22

Copyright © 2006-2009, Zend Technologies Inc.
1.Download and install Zend Framework (if you haven't already)
2.Set the project path
3.Create the project
4.Add ZF to the project, either recursively copied or symlinked to the project's
library/ directory
5.Check (edit) the Bootstrap
6.Configure the application (adjust settings for PHP environment)
7.Add controllers beyond those created by default
8.Add/edit View scripts
… You should be able to generate a Welcome Page at this point
| 22
Steps to RAD: Phase 1


ZF Fundamentals | Participant Guide
© 2006-2009 Zend Technologies, Inc.
22
Slide 23

Copyright © 2006-2009, Zend Technologies Inc.
| 23
Create the Project

Navigate to the directory you want to contain
the new project, and execute the "create"
command – this produces the basic site
structure

Could also use Zend Studio to create the
project… even easier
Hello, World!



Here are the two create commands for different environments


Using Studio to create the project is extremely simple – choose New > Framework Project

Participant Guide | ZF Fundamentals
23
© 2006-2009 Zend Technologies, Inc.
Slide 24

Copyright © 2006-2009, Zend Technologies Inc.
1.Download and install Zend Framework (if you haven't already)
2.Set up ZF Command Line Tool
3.Create the project
4.Add ZF to the project, either recursively copied or symlinked to the project's
library / directory
5.Check (edit) the Bootstrap
6.Configure the application (adjust settings for PHP environment)
7.Add controllers beyond those created by default
8.Add/edit View scripts
… You should be able to generate a Welcome Page at this point
| 24
Steps to RAD: Phase 1


ZF Fundamentals | Participant Guide
© 2006-2009 Zend Technologies, Inc.
24
Slide 25

Copyright © 2006-2009, Zend Technologies Inc.
| 25
Add ZF to the Library

If Zend Framework is not already part of the include_path, you
should either copy or symlink the library/Zend/directory of the
ZF installation into the library/ directory of the project

Example (Unix):
Hello, World!



If Zend Framework is not already part of the include_path, you should either copy or symlink it into
the library/ directory


In either case, you'll want to either recursively copy or symlink the library/Zend/ directory of your
Zend Framework installation into the library/ directory of your project


On Unix-like systems, that would look like one of the above code examples

Participant Guide | ZF Fundamentals
25
© 2006-2009 Zend Technologies, Inc.
Slide 26

Copyright © 2006-2009, Zend Technologies Inc.
1.Download and install Zend Framework (if you haven't already)
2.Set up ZF Command Line Tool
3.Create the project
4.Add ZF to the project, either recursively copied or symlinked to the project's
library/ directory
5.Check (edit) the Bootstrap
6.Configure the application (adjust settings for PHP environment)
7.Add controllers beyond those created by default
8.Add/edit View scripts
… You should be able to generate a Welcome Page at this point
| 26
Steps to RAD: Phase 1


ZF Fundamentals | Participant Guide
© 2006-2009 Zend Technologies, Inc.
26
Slide 27

Copyright © 2006-2009, Zend Technologies Inc.
|
27
• Examine the Bootstrap file in Studio:
Bootstrap file
Hello, World!



The bootstrap file is the page all requests are routed through -- html/index.php in this case


This will instantiate and dispatch the front controller, which routes requests to action controllers... We
will study the Front Controller in depth in succeeding modules

Participant Guide | ZF Fundamentals
27
© 2006-2009 Zend Technologies, Inc.
Slide 28

Copyright © 2006-2009, Zend Technologies Inc.
1.Download and install Zend Framework (if you haven't already)
2.Set up ZF Command Line Tool
3.Create the project
4.Add ZF to the project, either recursively copied or symlinked to the project's
library/ directory
5.Check (edit) the Bootstrap
6.Configure the application (adjust settings for PHP environment)
7.Add controllers beyond those created by default
8.Add/edit View scripts
… You should be able to generate a Welcome Page at this point
| 28
Steps to RAD: Phase 1


ZF Fundamentals | Participant Guide
© 2006-2009 Zend Technologies, Inc.
28
Slide 29

Copyright © 2006-2009, Zend Technologies Inc.
|
29
public/.htaccess File
• Let's review the public/.htaccess file, which
is automatically generated:
Hello, World!


Participant Guide | ZF Fundamentals
29
© 2006-2009 Zend Technologies, Inc.
Slide 30

Copyright © 2006-2009, Zend Technologies Inc.
|
30
index.php (Environment)
Hello, World!


ZF Fundamentals | Participant Guide
© 2006-2009 Zend Technologies, Inc.
30
Slide 31

Copyright © 2006-2009, Zend Technologies Inc.
1.Download and install Zend Framework (if you haven't already)
2.Set up ZF Command Line Tool
3.Create the project
4.Add ZF to the project, either recursively copied or symlinked to the project's
library/ directory
5.Check (edit) the Bootstrap
6.Configure the application (adjust settings for PHP environment)
7.Add controllers beyond those created by default, as needed
8.Add/edit View scripts
… You should be able to generate a Welcome Page at this point
| 31
Steps to RAD: Phase 1



Note that in the simple example we are using – "Hello, World" – no other controllers are needed


That is the great thing about RAD – it creates all the basics

Participant Guide | ZF Fundamentals
31
© 2006-2009 Zend Technologies, Inc.
Slide 32

Copyright © 2006-2009, Zend Technologies Inc.
• This is how requests are routed in Zend Framework… more on this later…
• Open application/ controllers/ IndexController.php:
(As noted earlier, both the default controller and default action called are index)
|
32
Default Action Controller
http://www.example.com / controller / action / param1/ value1/ param2/ value2
Hello, World!


ZF Fundamentals | Participant Guide
© 2006-2009 Zend Technologies, Inc.
32
Slide 33

Copyright © 2006-2009, Zend Technologies Inc.
|
33
Error Controller
Hello, World!



By default, the error handler plugin is registered; this plugin expects that a controller exists to handle
errors


By default, it assumes an ErrorController in the default module with an errorAction method


With the displayed layout, this file will go into application/controllers/ErrorController.php

Participant Guide | ZF Fundamentals
33
© 2006-2009 Zend Technologies, Inc.
Slide 34

Copyright © 2006-2009, Zend Technologies Inc.
1.Download and install Zend Framework (if you haven't already)
2.Set up ZF Command Line Tool
3.Create the project
4.Add ZF to the project, either recursively copied or symlinked to the project's
library/ directory
5.Check (edit) the Bootstrap
6.Configure the application (adjust settings for PHP environment)
7.Add controllers beyond those created by default
8.Add / edit View scripts
… You should be able to generate a Welcome Page at this point
| 34
Steps to RAD: Phase 1


ZF Fundamentals | Participant Guide
© 2006-2009 Zend Technologies, Inc.
34
Slide 35

Copyright © 2006-2009, Zend Technologies Inc.
|
35
View Script
Hello, World!



Only a simple update to the text is needed for this "Hello, World" example


As mentioned previously, view scripts are found in application/views/scripts/


The view script for the default controller and action is in
application/views/scripts/index/index.phtml


Create this file, and add this HTML

Participant Guide | ZF Fundamentals
35
© 2006-2009 Zend Technologies, Inc.
Slide 36

Copyright © 2006-2009, Zend Technologies Inc.
|
36
Error View Script
Hello, World!



This example provides sample code for creating a view script for the error controller…


Note that this script is really designed for post-deployment, as it provides no information as to the
nature of the error… we’ll look at this later, in more depth

ZF Fundamentals | Participant Guide
© 2006-2009 Zend Technologies, Inc.
36
Slide 37

Copyright © 2006-2009, Zend Technologies Inc.
|
37

Now view your application!
 This is just a start…
 There are many ways to make applications more robust by adding
complexity through Zend Framework and MVC
 Note that we have only written shells of Controllers so far
Exercise Wrap-Up
:
Hello, World!


Participant Guide | ZF Fundamentals
37
© 2006-2009 Zend Technologies, Inc.
Slide 38

Copyright © 2006-2009, Zend Technologies Inc.
|
38
Development vs
.
Production
Best Practice:
• Change the application configuration to switch from displaying the stack trace
to displaying the error only
• Do you remember in which file this code appears?
Answer:
• This is set in the .htaccess file
SetEnv APPLICATION_ENV development
• You can look back at the Error View Script to see the conditional code
Hello, World!


ZF Fundamentals | Participant Guide
© 2006-2009 Zend Technologies, Inc.
38
Slide 39

Copyright © 2006-2009, Zend Technologies Inc.
So, What Exactly is RAD?
• You have just seen how ZF can help you to create a web application quickly
using its Rapid Application Design feature
• While we cannot discuss this feature in-depth at a beginner's level, we will
take a brief look at the two main components behind this feature:
Zend_Tool and Zend_Application
| 39


Participant Guide | ZF Fundamentals
39
© 2006-2009 Zend Technologies, Inc.
Slide 40

Copyright © 2006-2009, Zend Technologies Inc.
| 40
Zend_Tool
• Zend_Tool provides a command-line script that facilitates common project-
related tasks:
• Setting up the project tree
• Adding controllers, actions (and related view scripts), model classes, etc
• Zend_Tool is extended by Zend_Tool_Framework and
Zend_Tool_Project
• Zend_Tool_Framework is a framework for exposing common
functionalities -the creation of project scaffolds, code generation, search
index generation, …
• Zend_Tool_Project builds on and extends the capabilities of
Zend_Tool_Framework to that of managing a "project"
• The "mechanics" of how Zend_Tool works is covered in the ZF Advanced
course



More advanced users can create their own tool providers that can then be directly invoked from that
script, or create their own RPC endpoints to expose the tooling on the web or via a web service

ZF Fundamentals | Participant Guide
© 2006-2009 Zend Technologies, Inc.
40
Slide 41

Copyright © 2006-2009, Zend Technologies Inc.
| 41
Zend_Tool_Framework
• Zend_Tool_Framework provides:

Common interfaces and abstracts

Base client functionality

Provider and Manifest interfaces

An Introspective Loading system

A standard set of System Providers
• Zend_Tool_Framework functionality can be written and exposed via PHP
classes dropped into the PHP include_path
• This provides considerable flexibility in implementation
• The functionality can be consumed by writing implementation and/or protocol-
specific clients (console clients, XML-RPC, SOAP, …)



Common interfaces and abstracts allow developers to create functionality and capabilities that can be
dispatched by tooling clients


Base client functionality and a concrete console implementation connect external tools and interfaces
to the Zend_Tool_Framework

The Console client may be used in CLI environments such as UNIX shells and the Windows
console

• "Provider" and "Manifest" interfaces can be utilized by the tooling system

Providers represent the functional aspect of the framework, and define the actions that
tooling clients may call

Manifests act as metadata registries that provide additional context for the various defined
providers

An introspective loading system scans the environment for Providers and determine what is required to
dispatch them

• A standard set of system providers allow the system to report its full capabilities status as well as
provide useful feedback; this includes a comprehensive "Help System"

Participant Guide | ZF Fundamentals
41
© 2006-2009 Zend Technologies, Inc.
Slide 42

Copyright © 2006-2009, Zend Technologies Inc.
| 42
• Use what you have learned to correctly match these terms with their
definitions…
Check Your Understanding
Term Match?Definition
A Tooling Client Zend_Tool_Framework subsystem that
exposes an interface such that tooling clients
can connect, query and execute commands
B Provider Set of providers for creating and maintaining
Zend Framework-based projects
C Zend_Tool_Framework Tooling client for the command line
D Client Subsystem and collection of built-in
functionality that the framework exports
E Manifest Framework which exposes tooling
capabilities
F Zend_Tool_Project Provider Developer tool that connects to and
consumes Zend_Tool_Framework
G Console Client/Command
Line Interface/zf.php
Subsystem for defining, organizing, and
disseminating provider requirement data


ZF Fundamentals | Participant Guide
© 2006-2009 Zend Technologies, Inc.
42
Slide 43

Copyright © 2006-2009, Zend Technologies Inc.
| 43
Zend_Application
• Zend_Application provides a standard, object-oriented method for
bootstrapping applications
• Bootstraps may define their own initialization resources, or draw upon some
common plugins to do their work
• Additionally, resources may be bootstrapped individually, allowing you to
utilize a common bootstrap with multiple gateway scripts tailored for different
tasks


Participant Guide | ZF Fundamentals
43
© 2006-2009 Zend Technologies, Inc.
Slide 44

Copyright © 2006-2009, Zend Technologies Inc.
| 44
Zend_Application
When developing applications, you often want to reuse the same code to
bootstrap your tests, a cronjob, or a service script
• Could simply include the bootstrap script
• But, usually, there are initializations that are environment specific – you
may not need the full MVC structure for a cronjob, or just the DB layer
for a service script
• Zend_Application aims to make code reuse easier by encapsulating
bootstrapping into OOP paradigms



Getting an MVC application configured and ready to dispatch has required an increasing amount of
code as more features become available:

setting up the database

configuring your view and view helpers

configuring your layouts

registering plugins

registering action helpers
and more…


Additionally, you will often want to reuse the same code to bootstrap your tests, a cronjob, or a
service script


While it's possible to simply include your bootstrap script, oftentimes there are initializations that are
environment specific – you may not need the MVC for a cronjob, or just the DB layer for a service
script

ZF Fundamentals | Participant Guide
© 2006-2009 Zend Technologies, Inc.
44
Slide 45

Copyright © 2006-2009, Zend Technologies Inc.
| 45
Zend_Application
• Zend_Application is broken into three functional areas:
1) Zend_Application:
loads the PHP environment, including include_paths and
autoloading, and instantiates the requested bootstrap class
2) Zend_Application_Bootstrap:
provides interfaces for bootstrap classes
....
Zend_Application_Bootstrap_Bootstrap:
provides common functionality for most bootstrapping needs, including
dependency checking algorithms and the ability to load bootstrap
resources on demand


Participant Guide | ZF Fundamentals
45
© 2006-2009 Zend Technologies, Inc.
Slide 46

Copyright © 2006-2009, Zend Technologies Inc.
| 46
Zend_Application_Bootstrap
• Create a bootstrap class for the application by extending
Zend_Application_Bootstrap_Bootstrap
• Minimally, could implement
Zend_Application_Bootstrap_Bootstrapper


ZF Fundamentals | Participant Guide
© 2006-2009 Zend Technologies, Inc.
46
Slide 47

Copyright © 2006-2009, Zend Technologies Inc.
| 47
Zend_Application_Bootstrap
• The entry point (example: public/index.php) will load Zend_Application
and instantiate it by passing:
• The current environment
• Options for bootstrapping


Participant Guide | ZF Fundamentals
47
© 2006-2009 Zend Technologies, Inc.
Slide 48

Copyright © 2006-2009, Zend Technologies Inc.
| 48
Zend_Application_Bootstrap
• The bootstrap options include the path to the file containing the bootstrap class
and optionally:

Any extra include_paths to set

Any additional autoloader namespaces to register

Any php.ini settings to initialize

The class name for the bootstrap class (if not "Bootstrap")

Resource prefix to path pairs to use

Any resources to use (by class name or short name)

Additional path to a configuration file to load

Additional configuration options:
• An array, a Zend_Config object, or the path to a configuration file


ZF Fundamentals | Participant Guide
© 2006-2009 Zend Technologies, Inc.
48
Slide 49

Copyright © 2006-2009, Zend Technologies Inc.
| 49
Zend_Application_Bootstrap_Bootstrapper
Zend_Application_Bootstrap_Bootstrapper defines the following API:
This API allows the bootstrap to accept the environment and configuration from
the application object, report the resources its responsible for bootstrapping, and
then bootstrap and run the application


Participant Guide | ZF Fundamentals
49
© 2006-2009 Zend Technologies, Inc.
Slide 50

Copyright © 2006-2009, Zend Technologies Inc.
| 50
Zend_Application_Resource
3) Zend_Application_Resource
provides an interface for standard bootstrapping resources that can be
loaded on demand by a bootstrap instance, as well as several default
resource implementations


ZF Fundamentals | Participant Guide
© 2006-2009 Zend Technologies, Inc.
50
Slide 51

Copyright © 2006-2009, Zend Technologies Inc.
| 51
Zend_Application and Zend_Loader_Autoloader
• Zend_Application is dependent upon Zend_Loader_Autoloader
• Zend_Loader_Autoloader replaces Zend_Loader::autoload()
!
• It provides the ability to manage a stack of namespaced autoloaders,
working around some minor issues of the SPL's autoloader as well as
providing opportunistic matching of namespace prefixes to match your
classes quickly
• A subcomponent, Zend_Loader_Autoloader_Resource,provides a
simple mechanism for mapping classes to the filesystem when the directory
structure may not exactly correspond to the class name
• By using an autoloader by default, you can help your code perform better
as well as leave class resolution out of your code
• This greatly expedites application development



Zend_Loader_Autoloader has solved many of the reported user issues with
Zend_Loader::autoload()

• Zend_Loader::registerAutoload() now proxies to Zend_Loader_Autoloader, and marks
the instance as a fallback autoloader
• This will ensure equivalent functionality, and reduces the number of deprecation notices
emitted to one

Participant Guide | ZF Fundamentals
51
© 2006-2009 Zend Technologies, Inc.
Slide 52

Copyright © 2006-2009, Zend Technologies Inc.Copyright © 2006-2009, Zend Technologies Inc.
MOD 3: MVC Design Pattern


ZF Fundamentals | Participant Guide
© 2006-2009 Zend Technologies, Inc.
52
Slide 53

Copyright © 2006-2009, Zend Technologies Inc.
| 53
MVC Design Pattern
• The Model-View-Controller pattern, is now a standard in web application design

Zend Framework provides a simple, easy-to-use MVC model

In this course, we present one way of implementing this design pattern, with
a view to Best Practices… keep in mind it is not the only way…


Why Use the MVC Design Pattern?

It is a simple solution for most web applications

It is flexible and extensible

It supports advanced applications... Separating out the logic makes running complex applications
simpler because the code is easier to manage

It is a best practice for application workflow


Participant Guide | ZF Fundamentals
53
© 2006-2009 Zend Technologies, Inc.
Slide 54

Copyright © 2006-2009, Zend Technologies Inc.
| 54
MVC Elements
• Code falls under one of three categories:
View
View
Model
Model
MVC models it…
Presentation
Business Logic
Data Access
Controller
Controller



The MVC pattern models the same separation of code into three categories: Presentation,
Business Logic, and Data Access


The end result is that the presentation code can be consolidated in one part of your application,
with the business logic in another and the data access code in yet another


Many developers find this well-defined separation indispensable for keeping their code organized,
especially when more than one developer is working on the same application

ZF Fundamentals | Participant Guide
© 2006-2009 Zend Technologies, Inc.
54
Slide 55

Copyright © 2006-2009, Zend Technologies Inc.
| 55
Because the MVC pattern
models the same separation of
code into three categories…
Presentation
Business Logic
Data Access
… the presentation code can be
consolidated into one part of
the application, the business
logic in another, and the data
access code in yet another
MVC Structure
View
View
Model
Model
Controller
Controller



Zend Framework does the routing work for you… provide a URL and the Framework takes care of
the routing request to the proper Controller, to implement the logic

Participant Guide | ZF Fundamentals
55
© 2006-2009 Zend Technologies, Inc.
Slide 56

Copyright © 2006-2009, Zend Technologies Inc.
Model
| 56
MVC Design Pattern: The View Function
The View defines
exactly what is
presented to the
user.
Controllers usually
pass data to each
view, to render in a
specified format.
Views will often
collect data from the
user. This is where
you are likely to find
HTML markup in
MVC applications.
This user data can
be stored in a model.
MVC Design Pattern
View
View
Model
Model
Controller
Controller


ZF Fundamentals | Participant Guide
© 2006-2009 Zend Technologies, Inc.
56
Slide 57

Copyright © 2006-2009, Zend Technologies Inc.
| 57
MVC Design Pattern: The Model Function
The Model is the part of
the application that
defines its basic
functionality behind a
set of abstractions
Data access routines
and some business
logic can be defined in
the model
The model can provide
the view with stored
user data for
presentation
View
View
View
Model
Model
Controller
Controller


Participant Guide | ZF Fundamentals
57
© 2006-2009 Zend Technologies, Inc.
Slide 58

Copyright © 2006-2009, Zend Technologies Inc.
| 58
MVC Design Pattern: The Controller Function
Controllers bind the
whole thing together…
They:
• Manipulate models
• Decide which view to
display based on the
user’s request and
other factors and
• Pass along the data
that each view will
need
• Optionally handoff
control to another
controller entirely
Model
View
View
View
Model
Model
Controller
Controller
Controller
Controller2


• Most MVC experts recommend keeping controllers as ‘skinny’ as possible

ZF Fundamentals | Participant Guide
© 2006-2009 Zend Technologies, Inc.
58
Slide 59

Copyright © 2006-2009, Zend Technologies Inc.
| 59
Variations on the MVC Pattern
A “Model” or “View” isn’t
absolutely necessary to gain
most of the benefit from
using the MVC pattern
• You can always perform
queries from a Controller
• You can always print output
from a Controller
Although not necessary, they
are highly recommended for
most situations
View
View
Model
Model
Controller
Controller



Although the pattern dictates three individual class types, they are conceptual as well as functional


For instance, a “model” or “view” isn’t absolutely necessary to gain most of the benefit from using the
MVC pattern


Although not required, they are highly recommended for most situations

Participant Guide | ZF Fundamentals
59
© 2006-2009 Zend Technologies, Inc.
Slide 60

Copyright © 2006-2009, Zend Technologies Inc.
| 60
Model-View-Controller : Program Flow
Web Server
Chaining
Request is sent to
index.php
index.php loads;
executes MVC
ZF parses and
routes request to
appropriate
Controller
Controller receives
and processes
request, using Model
objects as needed
Controller calls View
component to render
appropriate content
Models handle logic
for data requests;
Controller modifies
Controller
Model
View
(HTML)


ZF Fundamentals | Participant Guide
© 2006-2009 Zend Technologies, Inc.
60
Slide 61

Copyright © 2006-2009, Zend Technologies Inc.
| 61
How MVC is Mapped to the Web
• To implement MVC on the web, URLs must be mapped to Controllers
• Zend Framework uses the following approach…
http://www.example.com / controller/action/param1/value1/param2/value2
controller
maps to the ClassName of the
Controller Being executed
action
maps to the Method of the
chosen controller to execute
Parameters
can be passed as shown
in key / value pairs



By default, the first segment of a URL path maps to a controller, and the second to an action.

If no action is provided, the action index is assumed

If no controller is provided, the controller index is assumed (following the Apache
convention that maps a DirectoryIndex automatically)


Zend_Controller's dispatcher then takes the controller value and maps it to a class. By default, it
Title-cases the controller name and appends the word Controller.


Similarly, the action value is mapped to a method of the controller class. By default, the value is
lower-cased, and the word Action is appended.

Participant Guide | ZF Fundamentals
61
© 2006-2009 Zend Technologies, Inc.
Slide 62

Copyright © 2006-2009, Zend Technologies Inc.
| 62
Common Controllers
• You have already learned the basic function of a controller, and will study them
in much more detail in a later module
• For now, however, there are a few more things you need to know to be able to
complete this beginning exercise
• There are several controllers ubiquitous to web applications that utilize the MVC
design pattern:

Front Controller:Intercepts all requests, and maps them to individual controllers

Index Controller:Handles requests that are not explicitly routed to other controllers

Error Controller:Handles error conditions induced by uncaught exceptions when
throwExceptions is set to false (default)

Action Controller:Executes specifically requested business logic


ZF Fundamentals | Participant Guide
© 2006-2009 Zend Technologies, Inc.
62
Slide 63

Copyright © 2006-2009, Zend Technologies Inc.
First Look at the Front Controller
• It intercepts all requests, and maps them to individual controllers
• Controllers serving this function are usually called “Commands,” “Actions,”
“Action Controllers,” or “Page Controllers”

Zend Framework calls them Action Controllers
• Many different ways to implement

Zend_Controller_Front is Zend Framework's implementation
| 63


Participant Guide | ZF Fundamentals
63
© 2006-2009 Zend Technologies, Inc.
Slide 64

ZF Project : Guest Book Application









ZF Fundamentals | Participant Guide
© 2006-2009 Zend Technologies, Inc.
64
Slide 65

Copyright © 2006-2009, Zend Technologies Inc.
| 65
Demonstration of Guest Book Application
• We will now take a look at the functionality
of the Guest Book application


Participant Guide | ZF Fundamentals
65
© 2006-2009 Zend Technologies, Inc.
Slide 66

Copyright © 2006-2009, Zend Technologies Inc.
| 66
Now that you’ve seen the Guest Book in
action, and given the architecture depicted,
can you guess what function these elements
have within the application?
• GuestbookController.php
• Guestbook.php (Model)
• sign.phtml
Guest Book Application: MVC Architecture



ZF Fundamentals | Participant Guide
© 2006-2009 Zend Technologies, Inc.
66
Slide 67

MOD 4: Controller Components of MVC
(Guest Book)


Participant Guide | ZF Fundamentals
67
© 2006-2009 Zend Technologies, Inc.
Slide 68

Copyright © 2006-2009, Zend Technologies Inc.
| 68
Controllers for the Guest Book Application
• First, we will look specifically at the ZF
components and functionality of the
Controller layer


ZF Fundamentals | Participant Guide
© 2006-2009 Zend Technologies, Inc.
68
Slide 69

Copyright © 2006-2009, Zend Technologies Inc.
| 69
Controller Layer ZF Components
Guest Book
Zend_Controller
Zend_Controller_Front


Participant Guide | ZF Fundamentals
69
© 2006-2009 Zend Technologies, Inc.
Slide 70

Copyright © 2006-2009, Zend Technologies Inc.
| 70
Zend_Controller
• Zend_Controller is the heart of Zend Framework's MVC system
• The system was built with extensibility in mind

by subclassing the existing classes

by writing new classes that implement the various interfaces and abstract
classes that form the foundation of the controller family of classes

by writing plugins or action helpers to augment or manipulate the
functionality of the system
• Ultimately, application developers only need to really care about the controllers
for application logic

The rest is provided by Zend Framework

Developer does have to create a Front Controller instance if using
Zend_Application



Understanding the implementation of Controllers is the most important part of the MVC framework

ZF Fundamentals | Participant Guide
© 2006-2009 Zend Technologies, Inc.
70
Slide 71

Copyright © 2006-2009, Zend Technologies Inc.
| 71
Zend_Controller_Front
• Zend_Controller_Front implements the Front Controller pattern used in MVC
applications. It…

Initializes the request environment

Routes incoming requests

Dispatches any discovered actions

Aggregates any response content

Returns the response when the process is complete
• Implements Singleton pattern
(single instance available at given time)
• Registers a plugin broker with itself
• Requires one or more paths to Action Controller directories

Loads ErrorHandler plugin and ViewRenderer action helper by default



We took a quick look at this component and functionality with the "Hello, World" exercise… now it will
be covered in-depth


Note that the Front Controller implements the Singleton pattern, meaning only a single instance of it
may be available at any given time

This allows it to also act as a registry on which the other objects in the dispatch process may
draw


Zend_Controller_Front registers a plug-in broker with itself, allowing various events it triggers to
be observed by plugins


In most cases, this gives the developer the opportunity to tailor the dispatch process to the site
without the need to extend the front controller to add functionality

Participant Guide | ZF Fundamentals
71
© 2006-2009 Zend Technologies, Inc.
Slide 72

Copyright © 2006-2009, Zend Technologies Inc.
Front Controller Structure
• Decompose the request, which may include the URI, HTTP headers, HTTP body
content, and more
• Use that information to map the request to the appropriate controller

This is often referred to as “routing”
| 72


ZF Fundamentals | Participant Guide
© 2006-2009 Zend Technologies, Inc.
72
Slide 73

Copyright © 2006-2009, Zend Technologies Inc.
Front Controller Architecture
• Zend_Controller_Front is composed of several objects, covering a number
of responsibilities:

Zend_Controller_Request:object that encapsulates the request
environment; for HTTP requests, this
includes the request URI; GET, POST,
and COOKIE variables; raw POST
bodies; and the web server
environment

Zend_Controller_Router:routing (decomposing the URL and
mapping to a controller and action)

Zend_Controller_Dispatcher:mapping the controller to a class file,
instantiating the controller class, and
dispatching the requested action
| 73


Participant Guide | ZF Fundamentals
73
© 2006-2009 Zend Technologies, Inc.
Slide 74

Copyright © 2006-2009, Zend Technologies Inc.
Front Controller Architecture
• Zend_Controller_Front is composed of several objects, covering a number
of responsibilities:

Zend_Controller_Action:individual action controllers

Zend_Controller_Response:object encapsulating the response,
including any content to return,
headers, and cookies

Zend_Controller_Plugin:plugin architecture for extending
Zend_Controller's capabilities
| 74


ZF Fundamentals | Participant Guide
© 2006-2009 Zend Technologies, Inc.
74
Slide 75

Copyright © 2006-2009, Zend Technologies Inc.
| 75
Bootstrap Architecture
• Functionally, Front Controllers execute controllers
• Mapping: three elements must exist for the application

A “Front Controller”

A Router

A Dispatcher
• These pieces tie the URL provided to a class implemented by the application
developer
Front Controller
Controllers


Participant Guide | ZF Fundamentals
75
© 2006-2009 Zend Technologies, Inc.
Slide 76

Copyright © 2006-2009, Zend Technologies Inc.
| 76
Bootstrap Architecture
• There are three steps from Request Start to Controller Execution
• These steps are hidden from the developer by Zend Framework

They can be accessed for custom functionality - flexibility is key
Front Controller
Router
Dispatcher
Controller


ZF Fundamentals | Participant Guide
© 2006-2009 Zend Technologies, Inc.
76
Slide 77

Copyright © 2006-2009, Zend Technologies Inc.
| 77
Bootstrap Architecture: Front Controller
• The Front Controller initializes the framework

All necessary configuration is done here

Initializes all of the required objects for the request

Good place to initialize request resources such as database connections
Front Controller
Router
Dispatcher
Controller


Participant Guide | ZF Fundamentals
77
© 2006-2009 Zend Technologies, Inc.
Slide 78

Copyright © 2006-2009, Zend Technologies Inc.
| 78
Bootstrap Architecture: Router
http://www.example.com / controller / action/ param1/ value1/ param2/ value2
• The Router is responsible for breaking up the URL and determining which
controller to execute
 For Apache, the request URI's PATH_INFO environment is inspected
 For other web servers, other server environment variables are inspected
 Ultimately, all populate the request with an action to execute
Router
Front Controller
Dispatcher
Controller


ZF Fundamentals | Participant Guide
© 2006-2009 Zend Technologies, Inc.
78
Slide 79

Copyright © 2006-2009, Zend Technologies Inc.
| 79
Bootstrap Architecture: Dispatcher
• The Dispatcher is responsible for acting on the data provided by the Router

Creates an instance of the Controller class being executed

Initializes the Controller

Executes the correct method within the Controller
Dispatcher
Front Controller
Router
Controller


Participant Guide | ZF Fundamentals
79
© 2006-2009 Zend Technologies, Inc.
Slide 80

Copyright © 2006-2009, Zend Technologies Inc.
| 80
Bootstrap Architecture: Controller
• Ultimately, the Controller is executed when the dispatcher creates an instance
and calls the method
• The Controller is developed by the application developer
• Maps models to views, updates models, etc.
• Action methods typically should be brief
Controller
Front Controller
Router
Dispatcher


ZF Fundamentals | Participant Guide
© 2006-2009 Zend Technologies, Inc.
80
Slide 81

Copyright © 2006-2009, Zend Technologies Inc.
| 81
Given this default URL format: http://framework.zend.com/manual/search
???maps to the name of a Controller class
???maps to an Action method in that class
A Basic Example...
 manual maps to the name of a Controller class
 search maps to an Action method in that class


Participant Guide | ZF Fundamentals
81
© 2006-2009 Zend Technologies, Inc.
Slide 82

Copyright © 2006-2009, Zend Technologies Inc.
| 82
Bootstrap Architecture: Dispatch Loop
• The Dispatcher runs in a loop, allowing you to call multiple Controller
actions in a single request
 Called “Chaining” of controllers, and referred to as the “dispatch loop”
• Allows you to separate your application into logical classes
 Example: A login controller is executed after the "business" controller
Controller
Front Controller
Router
Dispatcher



One of the values of MVC is the ability to chain actions together from multiple distinct controllers

Allows for clean separation between functional logic


In Zend Framework, you can forward from one Controller to the next

$this->_forward(‘action’,‘controller’, null, array());

Where array() is key/value parameter pairs to pass into the Controller


Note: The execution of the current action will complete before the next is executed… if you want
execution to stop, return immediately from the method

ZF Fundamentals | Participant Guide
© 2006-2009 Zend Technologies, Inc.
82
Slide 83

Copyright © 2006-2009, Zend Technologies Inc.
| 83
Bootstrap Architecture: Request / Response
• Starting with the Front Controller, the entire process has access to a “Request”
and a “Response” object
• Encapsulates all interaction between the user of the application and the
business logic
Request
Response
Router
Dispatcher
Controller
Front Controller


Handling Input / Output


Zend Framework provides a Request and Response object to the Controller


These objects should be used for accessing input / sending output from your application

Request object

getCookie()

getEnv()

getHeader()

getPost()

getQuery()

Response object

setBody()

appendBody()

setException()

setHeader()

setHttpResponseCode()

Participant Guide | ZF Fundamentals
83
© 2006-2009 Zend Technologies, Inc.
Slide 84

Copyright © 2006-2009, Zend Technologies Inc.
| 84
Bootstrap Architecture: Request Object
• The Request Object contains everything your Controllers will need from the
HTTP request

GET/POST variables

Cookies

Server

Path Info
Front Controller
Router
Dispatcher
Controller
Request
Response


ZF Fundamentals | Participant Guide
© 2006-2009 Zend Technologies, Inc.
84
Slide 85

Copyright © 2006-2009, Zend Technologies Inc.
| 85
Bootstrap Architecture: Response Object
• The Response Object is populated by your Controllers

Response HTML/XML/Binary data

Any Headers associated with the request

Any Cookies to be set on the server
Front Controller
Router
Dispatcher
Controller
Response
Request


Participant Guide | ZF Fundamentals
85
© 2006-2009 Zend Technologies, Inc.
Slide 86

Copyright © 2006-2009, Zend Technologies Inc.
| 86
Controller Execution Methods
Controller::init()
Controller::preDispatch()
Controller::myAction()
Controller::postDispatch()
The init() method is called when the Controller
is instantiated
The preDispatch() method is called
immediately prior to calling the action…useful for
performing controller authorization, etc.
The <actionName>Action() method is called
to execute an action... developed by the
application author – ex: loginAction()
The postDispatch() method is called
immediately following the action execution...
useful for catching disallowed chains, etc.


ZF Fundamentals | Participant Guide
© 2006-2009 Zend Technologies, Inc.
86
Slide 87

Copyright © 2006-2009, Zend Technologies Inc.
| 87
Controller Access Methods
• Controllers in Zend Framework provide a number of Access methods that can be
used to get at data within the system
getRequest() The Request object
getResponse() The Response object
_getParam() Returns a parameter passed on the URL, GET, or POST
_getAllParams() Returns an array of all passed parameters
_setParam() Set a Controller parameter
_hasParam() Determine if a parameter exists
_redirect() Redirects the user to a new URL
_forward() Specifies another Controller to execute


Participant Guide | ZF Fundamentals
87
© 2006-2009 Zend Technologies, Inc.
Slide 88

Copyright © 2006-2009, Zend Technologies Inc.
| 88
Controller Architecture and Workflow Diagram
Putting it all together…
• This diagram presents a
representative workflow for a
Controller system
• Design permits design flexibility
along with enough structure that
systems built around the base
Zend_Controller can share
conventions and code layout


ZF Fundamentals | Participant Guide
© 2006-2009 Zend Technologies, Inc.
88
Slide 89

Copyright © 2006-2009, Zend Technologies Inc.
|
89
Exercise: Forward Controllers

For this exercise you are given a Controller Forwarddemo with two actions:
 forward, forwardnow

You must create a new controller with a single action that displays “Hello,
World”

Then, you must use "Controller Chaining" so that when given this URL the
desired output is created
 http://hostname/forwarddemo/forward/


Participant Guide | ZF Fundamentals
89
© 2006-2009 Zend Technologies, Inc.
Slide 90

Copyright © 2006-2009, Zend Technologies Inc.
|
90
Solution
: Controller Chaining Exercise

In this exercise, the only way to generate the correct output was to realize that
the _forward() method doesn’t execute until the end of the current action

You had to force the action to end prematurely using the return statement


ZF Fundamentals | Participant Guide
© 2006-2009 Zend Technologies, Inc.
90
Slide 91

Copyright © 2006-2009, Zend Technologies Inc.
|
91
Code the Controller Components:
1.Create the application's project structure using
RAD; name the project GuestBook.work
2.Think about where these components would
appear in the app
• RAD automatically creates some controllers
for you… do you remember which ones?
3.Code the required controller components for
the application
• You can reference the map if you are
unsure what is required
4.Make sure to make a comment using /* --
before each of your coding pieces, so you can
reference what you have done later as you
code the next project
5.Test and Debug
Guest Book
Zend_Controller
Zend_Controller_Front


Participant Guide | ZF Fundamentals
91
© 2006-2009 Zend Technologies, Inc.
Slide 92

MOD 5: General Components of MVC
(Guest Book)


ZF Fundamentals | Participant Guide
© 2006-2009 Zend Technologies, Inc.
92
Slide 93

Copyright © 2006-2009, Zend Technologies Inc.
| 93
ZF General Components
Guest Book
Zend_Config
Zend_Session
Zend_Exception



Will begin our look at ZF components by first examining the core 'General' components, before
looking at those associated with a particular layer within the MVC design pattern (M <> V <> C)

Participant Guide | ZF Fundamentals
93
© 2006-2009 Zend Technologies, Inc.
Slide 94

Copyright © 2006-2009, Zend Technologies Inc.Copyright © 2006-2009, Zend Technologies Inc.
Zend_Config


ZF Fundamentals | Participant Guide
© 2006-2009 Zend Technologies, Inc.
94
Slide 95

Copyright © 2006-2009, Zend Technologies Inc.
| 95
Configuration Data
• Although Zend Framework itself is configuration-less, the applications built on
top of it may not be

For instance, database credentials are usually stored in some sort of
configuration file
• Zend Framework provides a means of dealing with configuration data
intelligently

A consistent configuration API for getting and setting configuration values

Multiple data stores for configuration data, including
• PHP arrays
•.ini files
• XML documents



Important Concept - ZF is configure-less, but the applications may not be…

Participant Guide | ZF Fundamentals
95
© 2006-2009 Zend Technologies, Inc.
Slide 96

Copyright © 2006-2009, Zend Technologies Inc.
| 96
Scalable Configuration Techniques
• One of the nice things about Zend_Config is that you don’t have to use .ini
or XML files at all

You can store the configuration values in an array
 This allows you to start off without a real configuration file and only use one if
needed

Reading a file with every request is considerably slower then using an array



Again, the concept of ‘use only what you need’ is the simplest way

ZF Fundamentals | Participant Guide
© 2006-2009 Zend Technologies, Inc.
96
Slide 97

Copyright © 2006-2009, Zend Technologies Inc.
| 97
Zend_Config
• Zend_Config is designed to simplify access to, and use of, configuration data
within applications
• It typically defines the application environment

Database adapter credentials

Caching options

Paths
• It provides a standard OOP interface to config files
INI files XML files PHP arrays
• For static configuration

configuration data made accessible through an associative array, which can be
multidimensional, to support organizing the data from general to specific

provides adapter classes Zend_Config_Ini and Zend_Config_Xml for
configuration data storage



Zend_Config simplifies the use of configuration data for web applications

provides a property-based interface for reading configuration data

supports a variety of hierarchical data storage formats

supports inheritance of configuration data from one section into another

provides a nested, object property syntax for accessing configuration data within
application code

OPERATION THEORY

Note:

Important not to confuse such in-memory modifications with saving configuration data out
to specific storage media

Tools for creating and modifying configuration data for various storage media are out of
scope with respect to Zend_Config

Third-party open source solutions are readily available for the purpose of creating and
modifying configuration data for various storage media


Adapter classes inherit from the Zend_Config class since they utilize its functionality

Participant Guide | ZF Fundamentals
97
© 2006-2009 Zend Technologies, Inc.
Slide 98

Copyright © 2006-2009, Zend Technologies Inc.
| 98
Zend_Config
• Zend_Config (continued)

If config data is instead contained within an array, the data can be passed to
the constructor to utilize a simple, object-oriented interface

User scripts can provide arrays directly to the Zend_Config constructor
without using an adapter class, when appropriate

Zend_Config implements the Countable and Iterator interfaces to
facilitate simple access to configuration data, allowing the use of the
count() function and PHP constructs such as foreach with
Zend_Config objects


OPERATION THEORY (continued)


The Zend_Config family of classes enables configuration data to be organized into sections


Zend_Config adapter objects may be loaded with a single specified section, multiple specified
sections, or all sections (if none are specified)


Zend_Config adapter classes support a single inheritance model that enables configuration data to
be inherited from one section of configuration data into another

This is to reduce or eliminate the need for duplicating configuration data for different
purposes

An inheriting section may also override the values that it inherits through its parent section

Like PHP class inheritance, a section may inherit from a parent section, which may inherit
from a grandparent section, and so on, but multiple inheritance (i.e., section C inheriting
directly from parent sections A and B) is not supported

ZF Fundamentals | Participant Guide
© 2006-2009 Zend Technologies, Inc.
98
Slide 99

Copyright © 2006-2009, Zend Technologies Inc.
| 99
Zend_Config
• Allows inheritance by section


Participant Guide | ZF Fundamentals
99
© 2006-2009 Zend Technologies, Inc.
Slide 100

Copyright © 2006-2009, Zend Technologies Inc.
| 100
• Allows pulling by section
Zend_Config



PHP code to retrieve the individual section



ZF Fundamentals | Participant Guide
© 2006-2009 Zend Technologies, Inc.
100
I
NSTRUCTOR
N
OTES


Slide 101

Copyright © 2006-2009, Zend Technologies Inc.
| 101
Things to know about Zend_Config
• By default, Read-Only access
• Each instance can be marked mutable
• Mutable config objects may be written to:
...but any changes will not be saved
To save config files, use Zend_Config_Writer



Generic code examples

Participant Guide | ZF Fundamentals
101
© 2006-2009 Zend Technologies, Inc.
Slide 102

Copyright © 2006-2009, Zend Technologies Inc.
| 102
Zend_Config_Ini
• Enables configuration data storage in a familiar INI format; can read them into
an application using nested object property syntax

parse_ini_file()

Key Separator
• Format is specialized to provide both the ability to have a hierarchy of
configuration data keys and allow inheritance among configuration data sections

Data hierarchies supported by separating keys with a period [.]

Sections can extend or inherit from another section by following the section
name with a colon [:] and the name of the section from which data are to
be inherited



parse_ini_file: Zend_Config_Ini utilizes the parse_ini_file() PHP function

Review this documentation to be aware of its specific behaviors, which propagate to
Zend_Config_Ini, such as how the special values of true, false, yes, no, and null are
handled


Key Separator: By default, the key separator character is the period character (.) - this can be
changed, however, by changing the $config key 'nestSeparator' when constructing the
Zend_Config_Ini object… for example …

<?php
require_once 'Zend/Config/Ini.php';
$config['nestSeparator'] = ':';
$config = new Zend_Config_Ini('/path/to/config.ini', 'staging', $config);

ZF Fundamentals | Participant Guide
© 2006-2009 Zend Technologies, Inc.
102
Slide 103

Copyright © 2006-2009, Zend Technologies Inc.
| 103
Example: Basic Use for Loading Config data from an INI file
Example: Zend_Config_Ini:



In this example, there are configuration data for both a production system and for a staging system


Because the staging system configuration data are very similar to those for production, the staging
section inherits from the production section


It is an arbitrary decision in this case, and could have been written conversely, with the production
section inheriting from the staging section. This may not be the case for more complex situations

Participant Guide | ZF Fundamentals
103
© 2006-2009 Zend Technologies, Inc.
Slide 104

Copyright © 2006-2009, Zend Technologies Inc.
| 104
Example (cont’d): Loading Staging Config data from the INI file is now simple…
Example: Zend_Config_Ini:



Next, assume that the application developer needs the staging configuration data from the INI file


It is a simple matter to load these data by specifying the INI file and the staging section

ZF Fundamentals | Participant Guide
© 2006-2009 Zend Technologies, Inc.
104
Slide 105

Copyright © 2006-2009, Zend Technologies Inc.
| 105
Example: Using Zend_Config_Xml


This example illustrates a basic use of Zend_Config_Xml for loading configuration data from an
XML file.


This example contains configuration data for both a production system and for a staging system.

Participant Guide | ZF Fundamentals
105
© 2006-2009 Zend Technologies, Inc.
Slide 106

Copyright © 2006-2009, Zend Technologies Inc.
|
106
Exercise: Using Zend_Config_Xml

Alter the code below to call the staging configuration data from the XML file
instead


ZF Fundamentals | Participant Guide
© 2006-2009 Zend Technologies, Inc.
106
Slide 107

Copyright © 2006-2009, Zend Technologies Inc.
|
107
Let’s look at how Zend_Config is used within the GB application
Zend_Config:
Guest Book


Participant Guide | ZF Fundamentals
107
© 2006-2009 Zend Technologies, Inc.
Slide 108

Copyright © 2006-2009, Zend Technologies Inc.
|
108
Code the General Components:
1.Think about where these
components would appear in the
application
2.Code the components with the
following requirements:
• Configure the DB connection
3.Make sure to make a comment
using /* -- before each of your
coding pieces, so you can
reference what you have done
later as you code the next project
4.Test and Debug
Guest Book
Zend_Config


ZF Fundamentals | Participant Guide
© 2006-2009 Zend Technologies, Inc.
108
Slide 109

Zend_Exception


Participant Guide | ZF Fundamentals
109
© 2006-2009 Zend Technologies, Inc.
Slide 110

Copyright © 2006-2009, Zend Technologies Inc.
| 110
Zend_Exception
• All exceptions thrown by ZF classes should be derived from the base class
Zend_Exception
• Example:



Refer to the Zend Framework Manual and individual components for more information as to which
methods throw exceptions, the circumstances for the exceptions, and which exception classes derive
from Zend_Exception.

ZF Fundamentals | Participant Guide
© 2006-2009 Zend Technologies, Inc.
110
Slide 111

Zend_Session


Participant Guide | ZF Fundamentals
111
© 2006-2009 Zend Technologies, Inc.
Slide 112

Copyright © 2006-2009, Zend Technologies Inc.
| 112
Zend_Session
• Within PHP applications, a Session represents a logical, 1:1 connection
between Server-side, persistent state data and a particular User Agent Client
(example, a web browser)
• Zend_Session helps to manage and preserve session data across multiple
page requests by the same client
• Unlike cookie data, this session data is not stored on the client side, and is only
shared in response to a client request
• It is stored on the Server side in $_SESSION[],which is managed by
Zend_Session, and manipulated by Zend_Session_Namespace accessor
objects



Since Zend_Session uses the normal PHP ext/session functions internally, and all the familiar
configuration options and settings apply (see http://www.php.net/session), with the bonus of
convenience through an object-oriented interface and defaults providing both best practices and
smooth integration with Zend Framework. Thus, a standard PHP session id, stored either in a client's
cookie or embedded in URLs, maintains the association between a client and session state data


The default ext/session save handler does not solve the problem of maintaining this association - if a
client can connect to any sever in a cluster of servers - since session state data is saved to the local
server only. A list of additional, appropriate save handlers will be provided, when available

ZF Fundamentals | Participant Guide
© 2006-2009 Zend Technologies, Inc.
112
Slide 113

Copyright © 2006-2009, Zend Technologies Inc.
| 113
Zend_Session_Namespace
• Zend_Session_Namespace instances provide the primary API for
manipulating session data in ZF
• Namespaces are used to segregate all session data

Default exists to store all session data as one namespace
• Zend_Session utilizes ext/session and its special $_SESSION superglobal
as the storage mechanism for session state data

NOTE:
While $_SESSION is still available in PHP's global namespace, developers should
refrain from directly accessing it, so that Zend_Session and
Zend_Session_Namespace can operate most effectively and securely



Zend_Session_Namespace creates instances of accessor objects for namespaced slices of
$_SESSION[]. The Zend_Session component wraps the existing PHP ext/session with an
administration and management interface, as well as providing an API for
Zend_Session_Namespace to persist session namespaces


Zend_Session_Namespace provides a standardized, object-oriented interface for working with
namespaces persisted inside PHP's standard session mechanism. Support exists for both
anonymous and "login" session namespaces


Zend_Auth, the authentication component of the ZF uses Zend_Session_Namespace to store
some information associated with authenticated users in the "Zend_Auth" namespace

Participant Guide | ZF Fundamentals
113
© 2006-2009 Zend Technologies, Inc.
Slide 114

Copyright © 2006-2009, Zend Technologies Inc.
| 114
Example – Counting Page Views Using the Default Namespace
Using Zend_Session:



If no namespace is specified when instantiating Zend_Session, all data will be transparently stored
in a namespace called "Default“


Zend_Session is not intended to work directly on the contents of session namespace containers -
instead, we use Zend_Session_Namespace


The example above demonstrates use of this default namespace, showing how to count the number
of times a user views pages on your website

ZF Fundamentals | Participant Guide
© 2006-2009 Zend Technologies, Inc.
114
Slide 115

Copyright © 2006-2009, Zend Technologies Inc.
|
115
Starting a Session:
If you want all requests to initiate a session, start it in the bootstrap file… Why?
This avoids the possibility that your session might be started after headers have been
sent to the browser, resulting in an exception and possible broken page for your viewers
Quick Check:
Which of the following four ways to start a session with ZF are valid, and which are not?
1.
Set PHP’s session.auto_start ini setting in either php.ini or
.
htaccess
2.
Use Zend_Session
::
start()
3.
Use PHP's session_start() function directly
4.
Use new Zend_Session_Namespace() whenever needed, and the session will be
automatically started within Zend_Session
Zend_Session Best Practices:






Participant Guide | ZF Fundamentals
115
© 2006-2009 Zend Technologies, Inc.
Same slide…

Copyright © 2006-2009, Zend Technologies Inc.
|
115
Starting a Session:
If you want all requests to initiate a session, start it in the bootstrap file… Why?
This avoids the possibility that your session might be started after headers have been
sent to the browser, resulting in an exception and possible broken page for your viewers
Quick Check:
Which of the following four ways to start a session with ZF are valid, and which are not?