Using Zend Framework 2 Sample
Using Zend Framework 2 Sample
Learn how to create modern web applications with PHP and Zend
Framework 2
Oleg Krivtsov
This book is for sale at http://leanpub.com/using-zend-framework-2
This version was published on 2013-12-27
This is a Leanpub book. Leanpub empowers authors and publishers with the Lean Publishing
process. Lean Publishing is the act of publishing an in-progress ebook using lightweight tools
and many iterations to get reader feedback, pivot until you have the right book and build
traction once you do.
2013 Oleg Krivtsov
Contents
Preface . . . . . . . . . . . .
About this Leanpub Book .
Your Feedback . . . . . . .
Subject of this Book . . . .
Audience of this Book . . .
Structure of the Book . . .
Examples and Source Code
Acknowledgments . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
i
i
ii
ii
ii
iii
iii
iv
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
1
1
2
3
4
4
6
6
7
8
8
9
12
13
16
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
18
18
19
21
23
25
26
29
29
4 Model-View-Controller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4.1 Get the Hello World Example from GitHub . . . . . . . . . . . . . . . . . . . . .
32
32
CONTENTS
4.2
32
Preface
About this Leanpub Book
This book is currently a work in progress. Thanks to Leanpub, you have a chance to obtain this
book at a lower cost and give your feedback to the author. This makes it possible for the author
to immediately correct mistakes and enhance the places in text that you point to, thus creating
a high-quality product.
For your patience, you will receive all newer versions of this book for free as they appear, and
the final version as soon as this book is complete.
The following table gives you some summary regarding this books current status:
Current Status of This Book
Book complete
Book version
Last updated
about 60%
0.5.1
Oct 28, 2013
Here is a recent working history to give you a feel for the authors writing speed:
Recent Change History
Date
Version
Description
2013/10/28
2013/10/12
0.5.2
0.5.1
2013/09/29
0.5
2013/09/08
0.4.1
2013/08/26
0.4
2013/07/30
0.3
2013/06/30
0.2
2013/06/17
0.1
2013/06/08
https://leanpub.com
Preface
ii
Your Feedback
Thank you for reading this book and helping to make it better. You are encouraged to point out
errors, make suggestions and critical remarks. You can write the author a message through the
dedicated Google Group. Your feedback is highly appreciated.
Preface
iii
JavaScript a client-side scripting language used for making a web page more interactive.
For learning HTML, CSS and JavaScript, a good starting point is W3Schools Tutorials.
iv
Preface
Acknowledgments
Thanks to Edu Torres, a 2D artist from Spain, for making the cover and an illustration for this
book. Also thanks to Moriancumer Richard Uy for helping the author to find and fix the mistakes
in the text.
Write secure web sites with ZF2-provided components like form input filters and validators, HTML output escapers and cryptography algorithms, human check (Captcha) and
Cross-Site Request Forgery (CSRF) form elements.
Figure 1.1. Zend Framework sits on top of PHP and contains reusable components for building your web site
1.2 License
Zend Framework 2 is licensed under BSD-like license, allowing you to use it in both commercial
and free applications. You can even modify the library code and release it under another name.
The only thing you cannot do is to remove the copyright notice from the code. If you use Zend
Framework 2, it is also recommended that you mention about it in your sites documentation or
on About page.
Below, the Zend Framework 2 license text is presented. As you can see, it is rather short.
http://framework.zend.com/blog
Date
Version
ZF 2.2.1
ZF 2.2.0 Stable
ZF 2.2.0rc3
ZF 2.2.0rc2
ZF 2.2.0rc1
ZF 2.1.5
ZF 2.1.5
ZF 2.1.4
ZF 2.1.3
ZF 2.1.2
ZF 2.1.1
ZF 2.1.0 Stable
ZF 2.0.7
ZF 2.0.6
ZF 2.0.5
ZF 2.0.4
ZF 2.0.3
ZF 2.0.2
ZF 2.0.1
ZF 2.0.0 Stable
1.4 Distributions
You can download the source code of Zend Framework 2 from the official site (presented in
figure 1.2) to become familiar with its structure and components.
ZF2 can be downloaded in two types: full and minimum. A full-size archive contains a complete
set of components plus demos; its size is about 3 Mb. Mimimum-size distribution contains library
components only, and its size is 3 Mb (also !).
In most cases you wont need to download the code of Zend Framework 2 manually.
Instead, you will install it with Composer dependency manager. We will become
familiar with Composer later in Chapter 2.
Documentation. Documentation for ZF2 is located by this address. It includes beginners tutorial,
programmers manual, and API reference (API stands for Application Programming Interface).
Community Forums. Zend Framework 2 has dedicated user groups all over the world. The list of
groups can be found on this page.
Webinars are video tutorials covering various ZF2 features. Complete list of webinars can be
http://framework.zend.com/learn/
http://framework.zend.com/participate/user-groups
ZF2 utilizes URL rewriting extension for redirecting web-users to entry script of your site
(you have to enable Apaches mod_rewrite module.) You may also need to install some PHP
extensions, like memory caching extension, to improve ZF2 performance. This can be a difficulty
when using a shared hosting and requires that you have admin rights on your server.
So, if you are planning to use ZF2 on a shared web hosting, think twice. The best server to install
ZF2 on is a server with the latest version of PHP and with shell access to be able to execute
Composer, install PHP extensions and provide an ability to schedule console PHP scripts by
cron.
If your company manages its own server infrastructure and can afford upgrading PHP version to
the latest one, you can install ZF2 on your private server. An acceptable alternative is installing a
ZF2-based web application to a cloud-based hosting service, like Amazon Web Services. Amazon
provides Linux server instances as a part of EC2 service. EC2 is rather cheap, and it provides a
free usage tier letting you try it for free for one year.
1.8 Security
Zend Framework 2 follows the best practices to provide you with a secure code base for your
web sites. ZF2 creators release security bug fixes on a regular basis. You can incorporate those
fixes with a single command through Composer dependency manager.
ZF2 provides many tools allowing to make your web site secure:
Routing allows to define strict rules on how an acceptable page URL should look like. If
a site user enters an invalid URL in a web browsers navigation bar, he is automatically
redirected to an error page.
Access control lists and Role-Based Access Control (RBAC) allow to define flexible rules
for granting or denying access to certain resources of your web site. For example, an
anonymous user would have access to your index page only, authenticated users would
have access to their profile page, and the administrator user would have access to site
management panel.
Form validators and filters ensure that no unwanted data is collected through web forms.
Filters, for example, allow to trim strings or strip HTML tags. Validators are used to
check that the data that had been submitted through a form conforms to certain rules.
For example, E-mail validator checks that an E-mail field contains valid E-mail address,
and if not, raises an error forcing the site user to correct the input error.
Captcha and CSRF (Cross-Site Request Forgery) form elements are used for human checks
and hacker attack prevention, respectively.
Escaper component allows to strip unwanted HTML tags from data outputted to site pages.
Cryptography support allows you to store your sensitive data (e.g. credentials) encrypted.
http://aws.amazon.com/
http://aws.amazon.com/free/
1.9 Performance
ZF2 creators have claimed to do a great job to improve performance of the ZF2 comparing to the
first version of the framework.
Lazy class autoloading. Classes are loaded once needed. You dont have to write require_once
for each class you want to load. Instead, the framework automatically discovers your classes
using the autoloader feature. Autoloader uses either class map or class naming conventions to
find and load the needed class.
Efficient plugin loading. In ZF2, plugin classes are instantiated only when they really need to.
This is achieved through service manager (the central repository for services of your application).
Support of caching. PHP has several caching extensions (like APC or Memcache) that can be used
to speed-up ZF2-based web sites. Caching saves frequently used data to memory to speed-up data
retrieval. For example, a Zend Framework 2 application consists of many files which require time
for PHP interpreter to process the files each time you open the page in the browser. You can use
APC extension to cache precompiled PHP opcodes to speed up your site. Additionally, you can
use the ZF2s event manager to listen to dispatching events, and cache HTML response data with
Memcache extension.
Are there any benchmark tests of ZF2 performance?
As per the authors knowledge, currently, there are no reliable benchmark tests that
would allow to compare ZF2 performance with performance of other frameworks.
Aspect Oriented Design pattern. In ZF2, everything is event-driven. When a site user
requests a page, an event is generated (triggered). A listener (or observer) can catch event
and do something with it. For example, a router service parses the URL and determines
what controller class to call. When the event finally reaches the page renderer, an HTTP
response is generated and the user sees the web page.
Singleton pattern. In ZF2, there is the service manager object which is the centralized
registry of all services available in the application. Each service exists in a single instance
only.
Strategy pattern. While browsing ZF2 documentation or source code, youll encounter the
word strategy for sure. A strategy is just a class encapsulating some algorithm. And you
can use different algorithms based on some condition. For example, the page renderer has
several rendering strategies, making it possible to render web pages differently based on
Accept HTTP header (the renderer can generate an HTML page, a JSON response, an RSS
feed etc.)
Adapter pattern. Adapters allow to adapt a generic class to concrete use case. For example,
Zend\Db component provides access to database in a generic way. Internally, it uses
adapters for each supported database (SQLite, MySQL, PostgreSQL and so on.)
Factory pattern. You can create an instance of a class using the new operator. Or you can
create it with a factory. A factory is just a class encapsulating creation of other objects.
Factories are useful, because they simplify dependency injection - you can provide a
generic factory interface instead of hard-coding the concrete class name. This simplifies
the testing of your model and controller classes.
1.11 Components
ZF2 developers believe that the framework should be a set of decoupled components with
minimum dependencies on each other. This is how ZF2 is organized.
The idea was to let you use some selected ZF2 components alone, even if you write your site with
another framework. This becomes even easier, keeping in mind that each component of ZF2 is
a Composer-installable package, so you can easily install any ZF2-component together with its
dependencies through a single command.
The table 1.2 lists ZF2 components with their brief description:
Table 1.2. Zend Framework 2 Components
Component Name
Description
Core Components
ZendCache
ZendCode
10
Component Name
Description
ZendConsole
ZendDi
ZendEventManager
ZendLoader
ZendModuleManager
ZendMvc
ZendServiceManager
ZendStdlib
ZendView
Persistence
ZendDom
Provides tools for working with DOM documents and structures. This
includes
querying DOM trees with CSS selectors and XPath.
ZendDb
ZendJson
ZendSerializer
User Management
ZendAuthentication
ZendPermissions
ZendSession
11
Component Name
Description
View Helpers
ZendBarcode
ZendCaptcha
ZendNavigation
ZendPaginator
ZendProgressBar
ZendEscaper
Smart class for escaping text output. Used to secure web site views.
ZendTag
ZendLog
ZendTest
Web Forms
ZendFilter
ZendForm
ZendInputFilter
ZendValidator
Web Services
ZendFeed
ZendLdap
ZendServer
ZendSoap
ZendXmlRpc
ZendHttp
ZendUri
12
Component Name
Description
Identifiers (URIs).
Mail
ZendMail
ZendMime
Miscellaneous
ZendConfig
Provides a nested object property based user interface for accessing the
configuration data within application code.
ZendCrypt
ZendFile
ZendI18n
ZendMath
ZendMemory
ZendText
ZendVersion
13
controllers and the assets (e.g. database tables, files etc.). A module can call classes from
other modules. You can install third-party modules and reuse your own modules across
applications.
Aspect Oriented Design. In ZF2, events are used to make it possible to decouple modules.
You can install a module, and it will just work by listening to events occurring in the
application without knowing about other modules. Events include bootstrapping, routing
and dispatching.
Namespaces. In ZF1, you worked with long underscore-separated class names like Zend_Controller_Action. In ZF2, PHP namespaces are used, so instead youll have something
like 'Zend\MVC\Controller\AbstractActionController', which can be easier to type
with auto-completion feature and easier to understand. Namespaces allow to define short
class names (aliases) and use them instead of full names. By convention, namespaces are
mapped to directory structure, making it easier to perform class autoloading.
Configuration. In ZF1, you had an application-level INI config file. In ZF2, each module
has its config file in a form of PHP array. At application level, module configs are finally
merged into a single large nested PHP array.
Service Manager. In ZF1, you had an application registry of classes, which allowed you
to access application services and even put your own class to the registry and use it later.
In ZF2, we have the service manager, which is a more complex version of the registry,
implementing lazy loading and dependency injection. With service manager, you can
register a service class and use it across your modules. For example, Doctrine ORM registers
the entity manager service which you can use to access the database across the module
controllers.
14
As we can see, Zend Framework 2 (the red line) was released not so long ago, and has yet to
become popular. The author believes that ZF2 has all the necessary qualities to become popular
over time.
Figure 1.4. Popularity of Zend Framework 2 comparing to the first version. Powered by Google Trends
If you are familiar with one of the above mentioned frameworks, in table 1.3 you can find the
comparison of features provided by those PHP frameworks. Capabilities of Zend Framework 2
are marked with bold.
15
Feature
ZF2
Symfony 2
Cake PHP
CodeIgniter
Yii
Current
version
Distribution
archive size
2.2.1
2.3.1
2.3.6
2.1.3
1.1.13
3 Mb
4.4 Mb
2.0 Mb
2.2 Mb
3.9 Mb
Installation
Composer
Composer
Archive
Archive
Archive
Compatibility
with
shared
hostings
Bad (requires
SSH and
vhosts)
Bad (requires
SSH and
vhosts)
Good
Good
Good
Monolithic or
componentbased?
Components
Components
Components
Components
Monolithic
Prefer
conventions
or configs?
Configuration Configuration
Conventions
Conventions
Conventions
Database
access
pattern
Data Mapper
Active Record
Traditional
Active Record,
or
Active Record
PDO
Yes
Yes
Yes
Any
Any
Blueprint CSS
Smarty/Twig
Any you
want,
or none
None or Prado
Yes (PHPUnit)
Yes (PHPUnit)
Yes (PHPUnit-
Database
Data Mapper
(Doctrine/ORM),(Doctrine/ORM)
Table
Gateway,
Row
Gateway
Yes
(Doctrineprovided)
Yes (Doctrine-
Bootstrap
Bootstrap
View
Template
Language
Any you
want, or
none at all
Twig
Unit testing
Yes
(PHPUnit)
Yes (PHPUnit)
Yes
(PHPUnit)
Yes (PHPUnit)
Yes
No
Yes (Selenium)
Yes
(Doctrineprovided)
Yes (Doctrine
Yes
No
Yes
migrations
CSS
Framework
support
Functional
testing
Database
fixtures
provided)
(recommended)
based)
bundle)
16
Zend Framework 2 can be considered as one of the most mature and established PHP
frameworks on the market. This allows to be sure that ZF2 creators wont stop to update
and support it unexpectedly.
The major way for installing ZF2 is through Composer dependency manager. Symfony 2
is similar to ZF2 in this sence. Other PHP frameworks utilize the conventional installation
from an archive.
ZF2 (as Symfony 2) has bad compatibility with shared hostings because of the Composerbased installation method and strict PHP version requirements. So, if you need to install
your website to a shared hosting, you probably need to contact the hostings support for
installation instructions.
ZF2 provides the sophisticated configuration methods, so you can fine-tune and override
any aspect of its work. Some other PHP frameworks prefer the conventions over
configuration way, making it easier for newbies to start developing websites.
For the presentation layer, ZF2 suggests the use of Twitter Bootstrap CSS Framework by
default. But this does not limit you on using any other CSS frameworks.
In ZF2, you can use several database access methods. And like in most PHP frameworks,
you can benefit from using an object-oriented way of managing the database (with
Doctrine ORM). Additionally, you can use Doctrine migrations mechanism for managing
the database schema in a standardized way.
Comparing to other frameworks, ZF2 provides good capabilities for unit- and functional
testing (based on PHPUnit framework). This makes it possible to automate the testing of
the code you write. For testing the database functionality, you can use Doctrine-provided
fixture mechanism.
1.14 Summary
A PHP framework is a library, giving you the code base and defining consistent ways of creating
web applications. Zend Framework 2 is a modern web development framework created by
the Zend Company, the vendor of PHP language. It provides the developers with outstanding
capabilities for building scalable and secure web sites. ZF2 is licensed under BSD-like license and
can be used for free in both commercial and open-source applications.
ZF2 is updated frequently, making your sites more resistant to vulnerabilities and security holes.
On its official site, ZF2 provides the documentation (tutorials and API reference), webinars,
community forums and commercial support services, like trainings and certification program.
ZF2 creators strive to improve the performance of ZF2 in comparison to the first version of the
framework. Among the features that contribute into the performance of ZF2, there are lazy class
autoloading and support of caching.
On the market, Zend Framework is not the only web development framework. ZF2 is positioned
as a good framework for corporate applications because of its pattern-based design and
scalability. However, you can use ZF2 in any-sized web application with great success.
https://groups.google.com/forum/#!forum/using-zend-framework-2-book
17
Unpack the downloaded ZIP archive to some directory. If you are programming in Linux, it is
recommended to unpack it in your home directory:
cp /path/to/downloaded/archive/ ZendSkeletonApplication-master.zip ~
cd ~
unzip ZendSkeletonApplication-master.zip
The commands above will copy the file ZendSkeletonApplication-master.zip archive that
youve downloaded to your home directory, then unpack the archive.
If you are using Windows, you can place the skeleton app directory anywhere in your
system, but ensure that file and directory access rights are sufficient for your web server
to read and write the directory and its files. Actually, if you dont put your files to
C:\Program Files, everything should be OK.
https://github.com/zendframework/ZendSkeletonApplication
19
20
Inside of the public directory, you can also find .htaccess file. Its main purpose is to define URL
rewriting rules, but you also can use it to define access rules for your web-site. For example, with
.htaccess you can grant access to your web-site from your own IP address only, or use HTTP
authorization to request users for username and password.
The public directory contains several subdirectories also publicly accessible by web-users:
css subdirectory contains all publicly accessible CSS files;
img subdirectory contains publicly accessible images (*.JPG, *.PNG, *.GIF, *.ICO, etc.);
21
and js subdirectory stores publicly accessible JavaScript files used by your web-pages.
Typically, files of jQuery library are placed here, but you can put your own JavaScript
files here, too.
Because the Zend Skeleton Application is stored on GitHub, inside of the directory structure,
you can find hidden .gitignore and .gitmodules files. These are GIT version control systems
files. You can ignore them (or even remove them if you do not plan to store your code in a GIT
repository).
Because we will later use the skeleton as the base for our Hello World application, lets rename
the ZendSkeletonApplication-master directory into helloworld, which also sounds shorter. In
Linux, you can do that with the following command:
mv ZendSkeletonApplication-master helloworld
http://jquery.com/
http://git-scm.com/
http://getcomposer.org/
https://packagist.org/
22
{
"name": "zendframework/skeleton-application",
"description": "Skeleton Application for ZF2",
"license": "BSD-3-Clause",
"keywords": [
"framework",
"zf2"
],
"homepage": "http://framework.zend.com/",
"require": {
"php": ">=5.3.3",
"zendframework/zendframework": ">2.2.0rc1"
}
}
What is JSON?
JSON (JavaScript Object Notation), is a text-based file format used for human-readable
representation of simple structures and nested associative arrays. Although JSON
originates from Java, it is used in PHP and in other languages, because it is convenient
for storing configuration data.
In that file, we see some basic info on the skeleton application (its name, description, license,
keywords and home page). You will typically change this info for your future web-sites. This
information is optional, so you can even safely remove it, if you do not plan to publish your web
application on Packagist catalog.
What is interesting for us now is the require key. The require key contains the dependencies
declarations for our application. We see that we require PHP engine version 5.3.3 or later and
Zend Framework 2.2.0 Release Candidate 1 or later.
The information contained in composer.json file is enough to locate the dependencies, download
and install them into the vendor subdirectory. Lets finally do that by typing the following
commands from your command shell (replace APP_DIR placeholder with your actual directory
name):
cd APP_DIR
php composer.phar self-update
php composer.phar install
The commands above will change your current working directory to APP_DIR, then self-update
the Composer to the latest available version, and then install your dependencies. By the way,
23
Composer does not install PHP for you, it just ensures PHP has an appropriate version, and if
not, it will warn you.
If you look inside the vendor subdirectory, you can see that it now contains a lot of files. Zend
Framework 2 files can be found inside the APP_DIR/vendor/zendframework/zendframework/library
directory (figure 2.3). Here you can encounter all the components that we described in Chapter
1 (Authentication, Barcode, etc.)
24
Currently, we have the skeleton application inside of home folder. To let Apache know about it,
we need to edit the virtual host file.
Virtual host file may be located at a different path, depending on your
operating system type. For example, in Linux Ubuntu it is located in
/etc/apache2/sites-available/000-default file. For OS-specific information
about virtual hosts, please refer to Appendix A.
Lets now edit the default virtual host file to make it look like below:
<VirtualHost *:80>
ServerAdmin webmaster@localhost
DocumentRoot /home/username/helloworld/public
<Directory />
Options FollowSymLinks
AllowOverride None
</Directory>
<Directory /home/username/helloworld/public/>
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
allow from all
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
LogLevel warn
</VirtualHost>
Line 1 of the file makes Apache to listen to all (*) IP addresses on port 80.
25
Line 2 defines the web masters E-mail address. If something bad happens to the site, Apache
sends an alert E-mail to this address. You can enter your E-mail here.
Line 4 defines the document root directory (APP_DIR/public). All files and directories under
the document root will be accessible by web-users. You should set this to be the absolute
path to skeleton applications public directory. So, the directories and files inside public (like
index.php, css, js, etc.) will be accessible, while directories and files above public directory
(like config, module, etc.) wont be accessible by web users, which enhances the security of the
web site.
Lines 5-8 define default access rules for directories. These rules are rather strict. The Options
FollowSymLinks directive allows Apache to follow symbolic links (in Linux, a symbolic links is
an analog of a shortcut in Windows). The AllowOverride None directive forbids overriding any
rules using .htaccess files.
Lines 9-14 define rules for the document root directory (APP_DIR/public). These rules override
the default rules mentioned above. For example, the AllowOverride All directive allows to
define any rules in .htaccess files. The Order allow,deny and allow from all control a threepass access control system, effectively allowing everyone to visit the site.
Line 16 defines the path to error.log file, which can be used to troubleshoot possible errors
occurring in your site code. Line 23 defines the logging level to use (the warn means that warnings
and errors will be written to log).
Lines 18-19 are comments and ignored by Apache. You mark comments with the hash (#)
character.
Zend Framework 2 utilizes Apaches URL rewriting module for redirecting web-users
to entry script of your web-site. Please ensure that your web-server has mod_rewrite
module enabled. For instructions on how to enable the module, please refer to Appendix
A.
26
27
28
In the Run Configuration page, it is recommended that you specify the way you run the web site
(Local Web Site) and web site URL (http://localhost). Keep the Index File field empty (because
we are using mod_rewrite, the actual path to your index.php file is hidden by Apache). If you
are seeing the warning message like Index File must be specified in order to run or debug project
in command line, just ignore it.
Click the Finish button to create the project. When the helloworld project has been successfully
created, you should see the project window (see the figure 2.7).
In the project window, you can see the menu bar, the tool bar, the Projects pane where your
project files are listed, and, in the right part of the window, you can see the code of the index.php
entry file.
Please refer to Appendix B for more NetBeans usage tips, including launching and interactively
debugging ZF2-based web sites.
Its time for some advanced stuff
Congratulations! Weve done the hard work of installing and running the Zend Skeleton
Application, and now its time to have a rest and read about some advanced things in
the last part of this chapter.
<?php
namespace Zend\Mvc;
3
4
// ...
5
6
7
8
9
10
11
12
/**
* Main application class for invoking applications.
*/
class Application
{
// ... class members were omitted for simplicity ...
}
30
You may notice that in example above we have the opening <?php tag which tells the
PHP engine that the text after the tag is a PHP code. In example above, when the file
contains only the PHP code (without mixing PHP and HTML tags), you dont need to
insert the closing ?> tag after the end of the code. Moreover, this is not recommended
and may cause undesired effects, if you occasionally add some character after the
closing ?> tag.
In Zend Framework 2, all classes belong to top-level Zend namespace. The line 2 defines
the namespace Mvc, which is nested into Zend namespace, and all classes of this component
(including the Application class shown in this example on lines 9-12) belong to this namespace.
You separate nested namespace names with the back-slash character (\).
In other parts of code, you reference the Application class using its full name:
<?php
$application = new \Zend\Mvc\Application;
It is also possible to use the alias (short name for the class) with the help of PHPs use statement:
<?php
// Define the alias in the beginning of the file.
use Zend\Mvc\Application;
// Later in your code, use the short class name.
$application = new Application;
Although the alias allows to use a short class name instead of the full name, its usage
is optional. You are not required to always use aliases, and can refer the class by its full
name.
Every PHP file of your application typically defines the namespace (except index.php entry
script and config files, which typically do not). For example, the main module of your site, the
Application module, defines its own namespace whose name equals to the module name:
<?php
namespace Application;
// ...
class Module
{
// ... class members were omitted for simplicity ...
}
31
4 Model-View-Controller
In this chapter, you will learn about the models, views and controllers (MVC). The web
application uses the MVC pattern to separate business logic from presentation. The goal of this
is to allow for code reusability and separation of concerns.
The Hello World is a complete web site which can be installed on your machine. To install the
example, you can either edit your default virtual host file or create a new one. After editing the
file, restart the Apache HTTP Server and open the web site in your web browser.
Model-View-Controller
33
Figure 4.1. The Hello World sample can be downloaded from GitHub
Since that time, PHP became object-oriented, and now you can organize your code into classes.
The Model-View-Controller (MVC) pattern is just a set of advices telling you how to organize
your classes in a better manner, to make them easy to maintain.
In MVC, classes implementing your business logic are called models, code snippets rendering
HTML pages are called views, and the classes responsible for interacting with user are called
controllers.
Views are implemented as code snippets, not as classes. This is because views are
typically very simple and contain only the mixture of HTML and inline PHP code.
The main objective of the MVC concept is to separate the business logic (models) from its
visualization (views). This is also called the separation of concerns, when each layer does its
specific tasks only.
By separating your models from views, you reduce the number of dependencies between them.
Therefore, changes made to one of the layers have the lowest possible impact on other layers.
This separation also improves the code reusability. For example, you can create multiple visual
representations for the same models.
Model-View-Controller
34
To better understand how this works, lets remember that any web site is just a PHP program
receiving an HTTP request from the web server, and producing an HTTP response. Figure 4.2
shows how an HTTP request is processed by the MVC application and how the response is
generated:
First, the site visitor enters an URL in his web browser, for example http://localhost, and
the web browser sends the request to the web server over the Internet.
Web servers PHP engine runs the index.php entry script. The only thing the entry script
does is creating the Zend\Mvc\Application class instance.
The application uses its router component for parsing the URL and determining to which
controller to pass the request. If the route match is found, the controller is instantiated and
its appropriate action method is called.
Model-View-Controller
35
In the controllers action method, parameters are retrieved from GET and POST variables.
To process the incoming data, the controller instantiates appropriate model classes and
calls their methods.
Model classes use business logic algorithms to process the input data and return the
output data. The business logic algorithms are application-specific, and typically include
retrieving data from database, managing files, interacting with external systems and so
on.
The result of calling the models are passed to the corresponding view script for the
rendering of the HTML page.
View script uses the model-provided data for rendering the HTML page.
Controller passes the resulting HTTP response to application.
Web server returns the resulting HTML web page to the users web browser.
The user sees the page in browser window.
Now you might have some idea how models, views and controllers cooperate to generate HTML
output. In the next sections, we describe them in more details.
The rest of this chapter is skipped in this free sample.