Documente Academic
Documente Profesional
Documente Cultură
i
Zend Framework
This tutorial will give you a quick introduction to Zend Framework and make you
comfortable with its various components.
Audience
This tutorial has been prepared for professionals who are aspiring to make a career in
Zend framework. This will give you enough understanding on how to create and develop
a website using Zend.
Prerequisites
Before proceeding with the various types of components given in this tutorial, it is being
assumed that the readers are already aware about what a Framework is. In addition to
this, it will also be very helpful if you have sound knowledge on HTML, PHP and the OOPS
concepts.
All the content and graphics published in this e-book are the property of Tutorials Point (I)
Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish
any contents or a part of contents of this e-book in any manner without written consent
of the publisher.
We strive to update the contents of our website and tutorials as timely and as precisely as
possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt.
Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of our
website or its contents including this tutorial. If you discover any errors on our website or
in this tutorial, please notify us at contact@tutorialspoint.com
i
Zend Framework
Table of Contents
About the Tutorial .................................................................................................................................... i
Audience .................................................................................................................................................. i
Prerequisites ............................................................................................................................................ i
Factory Method..................................................................................................................................... 15
Initializer Method.................................................................................................................................. 17
ii
Zend Framework
AbstractActionController ...................................................................................................................... 38
AbstractRestfulController...................................................................................................................... 39
AbstractConsoleController .................................................................................................................... 39
iii
Zend Framework
Example ................................................................................................................................................ 72
iv
Zend Framework
v
1. Zend Framework Introduction
Zend Framework
A PHP Web Framework is a collection of classes which helps to develop a web application.
Zend is one of the most popular PHP framework. It is an open-source MVC framework
for rapidly developing, modern web applications. Zend Framework has several loosely
coupled components, so it is referred to as Component Library. Zend Framework
provides any PHP stack and Zend server to run Zend framework applications.
Zend Studio is an IDE that includes features to integrate with Zend Framework. It provides
MVC view and code generation. The current Zend framework 3.0 includes new components
such as JSON RPC server, a XML to JSON converter, PSR-7 functionality, and compatibility
with PHP 7.
Zend Framework 2 is an open source framework for developing web applications and
services using PHP 5.3+. Zend Framework 2 uses 100% object oriented code and utilizes
most of the new features of PHP 5.3, namely Namespaces, Lambda Functions and
Closures.
Zend Framework 2 evolved from Zend Framework 1, a successful PHP framework with
over 15 million downloads. Zend Server has a free community version and a commercial
version.
Session management
Data encryption
1
Zend Framework
Zend Goals
Following are the goals of the Zend Framework.
Flexibility
Compatibility
Zend Applications
The following popular products are developed by using the Zend Framework.
Testing PHPUnit is integrated with Zend so you can easily test the framework.
In the next chapter, we will learn how to install the Zend Framework.
2
2. Zend Framework InstallationZend Framework
To install the Zend Framework, we must first install the Composer and the latest version
of PHP as shown in the following steps.
Install Composer: Zend uses Composer for managing its dependencies, so make
sure you have the Composer installed on your machine. If the Composer is not
installed, then visit the official website of Composer and install it.
Install the latest version of PHP: To get the maximum benefit of Zend
Framework, install the latest version of PHP. The minimum required version for the
Zend Framework 3 is PHP 5.6 or later.
Manual installation
Composer based installation
Manual Installation
Download the latest version of Zend Framework by visiting the following link
https://framework.zend.com/downloads/archives
Extract the content of the downloaded archive file to the folder you would like to keep it.
Once you have a copy of Zend Framework available in your local machine, your Zend
Framework based web application can access the framework classes. Though there are
several ways to achieve this, your PHP include_path needs to contain the path to the
Zend Framework classes under the /library directory in the distribution. This method
applies to Zend Framework version 2.4 and earlier only.
Each Zend Framework module / component can be installed individually as well. For
example, to install the MVC component of the Zend Framework, use the following
composer command
3
3. Zend Framework Skeleton Application
Zend Framework
Let us create a skeleton application using the Zend Framework MVC layer and module
systems.
$ cd /path/to/install
$ composer create-project -n -sdev zendframework/skeleton-application myapp
4
Zend Framework
5
Zend Framework
6
Zend Framework
Now that the application is installed, you can test it out immediately using the PHP's
built-in web server:
$ cd path/to/install/myapp
$ composer serve
7
Zend Framework
This will start the PHP built-in CLI server on port 8080. Once the development server is
started, you can visit the site at (http://localhost:8080/). The built-in CLI server is for
development only.
Unit Tests
To run the skeleton unit tests, type the following command in your terminal.
8
Zend Framework
Downloading: 100%
9
Zend Framework
10
Zend Framework
Now the testing support is enabled so you can run the test using the following command.
$ ./vendor/bin/phpunit
<VirtualHost *:80>
ServerName myapp.localhost
DocumentRoot /path/to/install/myapp/public
<Directory /path/to/install/myapp/public>
DirectoryIndex index.php
AllowOverride All
Order allow,deny
Allow from all
<IfModule mod_authz_core.c>
Require all granted
</IfModule>
</Directory>
</VirtualHost>
11
4. Zend Framework MVC Architecture
Zend Framework
Before proceeding with this chapter, let us have a brief understanding of MVC. A Model
View Controller is a software approach that separates the application logic from the
presentation. In practice, it permits the webpages to contain minimal PHP scripting since
the presentation is separate from it.
Model: Model represents the structure of the application data. Typically, model
classes contain functions that helps to retrieve, insert and update business
data in the back-end database (MySQL, PostgreSQL, etc.).
View: View is the presentation layer of the MVC Application. It gets the models
data through the Controller and display it as needed. It is loosely coupled to the
Controller and the Model and so, it can be changed without affecting either the
Model and the Controller.
Controller: The Controller is the main component of the MVC architecture. Every
request first hits the controller. In other words, the controller processes all the
request and serves as an intermediary between the Model, View, and any other
resources needed to process the HTTP request and to generate the response.
In the next chapter, we will understand the different concepts of the Zend Framework.
12
5. Zend Framework ConceptsZend Framework
Zend Framework is a collection of 60+ components. They are loosely connected with each
other. They can be used as both stand-alone component as well as a group of components
working as a single unit.
zend-servicemanager
zend-eventmanager and
zend-modulemanager.
They provide Zend components the ability to integrate with other components efficiently.
Event Manager It gives the ability to create event based programming. This
helps to create, inject and manage new events.
Service Manager It gives the ability to consume any services (PHP classes) from
anywhere with a little effort.
13
6. Zend Framework Service Manager
Zend Framework
The Zend Framework includes a powerful service locator pattern implementation called
zend-servicemanager. Zend framework extensively uses the service manager for all its
functionalities. The Service Manager provides a high-level abstraction for the Zend
Framework. It also integrates nicely with all the other components of the Zend Framework.
Example
First, all the services need to be registered into the service manager. Once the services
are registered into the server manager system, it can be accessed at any time with minimal
efforts. The service manager provides a lot of options to register the service. A simple
example is as follows:
use Zend\ServiceManager\ServiceManager;
use Zend\ServiceManager\Factory\InvokableFactory;
use stdClass;
The above code registers the stdClass into the system using the Factory option. Now,
we can get an instance of the stdClass at any time using the get() method of the service
manager as shown below.
use Zend\ServiceManager\ServiceManager;
$object = $serviceManager->get(stdClass::class);
The get() method shares the retrieved object and so, the object returned by calling the
get() method multiple times is one and the same instance. To get a different instance
every time, the service manager provides another method, which is the build() method.
14
Zend Framework
use Zend\ServiceManager\ServiceManager;
$a = $serviceManager->build(stdClass::class);
$b = $serviceManager->build(stdClass::class);
Factory method
Initializer method
Factory Method
A factory is basically any callable or any class that implements the FactoryInterface
(Zend\ServiceManager\Factory\FactoryInterface).
Let us create a simple class implementing the FactoryInterface and see how to register
the class.
class Test
{
public function __construct(stdClass $sc)
15
Zend Framework
{
// use $sc
}
}
The TestFactory uses a container to retrieve the stdClass, creates the instance of the Test
class, and returns it.
$test = $sc->get(Test::class);
The service manager provides a special factory called InvokableFactory to retrieve any
class which has no dependency. For example, the stdClass can be configured using the
InvokableFactory since the stdClass does not depend on any other class.
16
Zend Framework
$stdC = $sc->get(stdClass::class);
Another way to retrieve an object without implementing the FactoryInterfac or using the
InvokableFactory is using the inline method as given below.
The AbstractFactoryInterface defines a method to check whether the object can be created
at the requested instance or not. If object creation is possible, it will create the object
using the __invokemethod of the FactoryInterface and return it.
Initializer Method
The Initializer Method is a special option to inject additional dependency for already
created services. It implements the InitializerInterface and the signature of the sole
method available is as follows:
17
Zend Framework
In the above example, the method checks whether the instance is of type
EventManagerAwareInterface. If it is of type EventManagerAwareInterface, it sets the
event manager object, otherwise not. Since, the method may or may not set the
dependency, it is not reliable and produces many runtime issues.
Lazy Services
Lazy service is one of those services which will not be fully initialized at the time of
creation. They are just referenced and only initialized when it is really needed. One of the
best example is database connection, which may not be needed in all places. It is an
expensive resource as well as have time-consuming process to create. Zend framework
provides LazyServiceFactory derived from the DelegatorFactoryInterface, which can
produce lazy service with the help of the Delegator concept and a 3rd party proxy
manager, which is called as the ocramius proxy manager.
Plugin Manager
Plugin Manager extends the service manager and provides additional functionality like
instance validation. Zend Framework extensively uses the plugin manager.
For example, all the validation services come under the ValidationPluginManager.
18
Zend Framework
Configuration Option
The service manager provides some options to extend the feature of a service manager.
They are shared, shared_by_default and aliases. As we discussed earlier, retrieved
objects are shared among requested objects by default and we can use the build()
method to get a distinct object. We can also use the shared option to specify which service
to be shared. The shared_by_default is same as the shared feature, except that it
applies for all services.
The aliases option can be used to provide an alternative name to the registered services.
This have both advantages and disadvantages. On the positive side, we can provide
alternative short names for a service. But, at the same time, the name may become out
of context and introduce bugs.
aliases' => [
'std' => stdClass::class,
'standard' => 'std'
]
19
7. Zend Framework Event Manager
Zend Framework
All modern applications need solid and flexible event components. Zend Framework
provides one such component, zend-eventmanager. The zend-eventmanager helps to
design high level architecture and supports subject/observer pattern and aspect oriented
programming.
Listener - Any PHP callback. They are attached to the events and gets called when
the event is triggered. The default signature of Listener is
function(EventInterface $e)
EventInterface Class - Used to specify the event itself. It has methods to set and
get event information like name (set/getName), target (get/setTarget) and
parameter (get/setParams).
EventManager class - The instance of the EventManager tracks all the defined
events in an application and its corresponding listeners. The EventManager
provides a method, attach to attach listener to an event and it provides a method,
trigger to trigger any pre-defined event. Once trigger is called, EventManager calls
the listener attached to it.
Example
Let us write a simple PHP console application to understand the event manager concept.
Follow the steps given below.
20
Zend Framework
This method sets the current class into the given event manager ($events argument) and
then sets the event manager in local variable $events.
The next step is to write the getEventManager method in class Greeter as shown below:
The method gets the event manager from a local variable. if it is not available, then it
creates an instance of event manager and returns it.
21
Zend Framework
This method gets the event manager and fires / triggers events attached to it.
The next step is to create an instance of the Greeter class and attach a listener to its
method, greet.
$greeter->getEventManager()->attach('greet', function($e) {
$event_name = $e->getName();
$target_name = get_class($e->getTarget());
$params_json = json_encode($e->getParams());
The listener callback just prints the name of the event, target and the supplied parameters.
<?php
use Zend\EventManager\EventManagerInterface;
use Zend\EventManager\EventManager;
use Zend\EventManager\EventManagerAwareInterface;
class Greeter implements EventManagerAwareInterface
{
22
Zend Framework
protected $events;
$greeter->getEventManager()->attach('greet', function($e) {
$event_name = $e->getName();
$target_name = get_class($e->getTarget());
$params_json = json_encode($e->getParams());
printf("\"%s\" event of class \"%s\" is called." .
" The parameter supplied is %s\n",
$event_name,
23
Zend Framework
$target_name,
$params_json);
});
$greeter->greet("Hello");
Now, run the application in the command prompt php Greeter.php and the result will be
as follows:
The above sample application explains only the basics of an event manager. The Event
manager provides many more advanced options such as Listener Priority, Custom
Callback Prototype / Signature, Short Circuiting, etc. The Event manager is used
extensively in the Zend MVC framework.
24
8. Zend Framework Module System
Zend Framework
The Zend Framework provides a powerful module system. The module system has three
components. They are as follows:
Module Manager Once the Module Autoloader locates the modules, the module
manager fires a sequence of events for each module. The implementation of the
Module Manager is located at myapp/vendor/zendframework/zend-
modulemanager/src/ModuleManager.php.
Module Manager Listeners They can be attached to the events fired by the
Module Manager. By attaching to the events of module manager, they can do
everything from resolving and loading modules to performing complex work for
each modules.
module_root/
Module.php
autoload_classmap.php
autoload_function.php
autoload_register.php
config/
module.config.php
public/
images/
css/
js/
src/
<module_namespace>/
<code files>
test/
phpunit.xml
25
Zend Framework
bootstrap.php
<module_namespace>/
<test code files>
view/
<dir-named-after-module-namespace>/
<dir-named-after-a-controller>/
<.phtml files>
The structure is same as discussed in the previous chapter, but here it is generic. The
autoload_ files can be used as a default mechanism for autoloading the classes available
in the module without using the advanced Module Manager available in the
zend-modulemanager.
These autoload files are not required but recommended. In the skeleton application, we
have not used the autoload_ files.
Module Class
The Module class should be named Module and the namespace of the module class should
be Module name. This will help the Zend Framework to resolve and load the module
easily. The Application module code in the skeleton(myapp)
application,myapp/module/Application/src/Module.php is as follows:
namespace Application;
class Module
{
const VERSION = '3.0.2dev';
public function getConfig()
{
return include __DIR__ . '/../config/module.config.php';
}
}
The Zend Framework module manager will call the getConfig() function automatically
and will do the necessary steps.
26
9. Zend Framework Application Structure
Zend Framework
In this chapter, let us understand the structure of the Zend Framework application. The
structure of the myapp application is as follows:
composer.json
composer.lock
CONDUCT.md
config
application.config.php
autoload
development.local.php
development.local.php.dist
global.php
local.php.dist
README.md
zend-developer-tools.local-development.php
development.config.php
development.config.php.dist
modules.config.php
CONTRIBUTING.md
data
cache
module-classmap-cache.application.module.cache.php
docker-compose.yml
Dockerfile
LICENSE.md
module
Application
config
src
test
view
phpcs.xml
phpunit.xml.dist
public
27
Zend Framework
css
bootstrap.css
bootstrap.css.map
bootstrap.min.css
bootstrap.min.css.map
bootstrap-theme.css
bootstrap-theme.css.map
bootstrap-theme.min.css
bootstrap-theme.min.css.map
style.css
fonts
glyphicons-halflings-regular.eot
glyphicons-halflings-regular.svg
glyphicons-halflings-regular.ttf
glyphicons-halflings-regular.woff
glyphicons-halflings-regular.woff2
img
favicon.ico
zf-logo-mark.svg
index.php
js
bootstrap.js
bootstrap.min.js
jquery-3.1.0.min.js
web.config
README.md
TODO.md
Vagrantfile
vendor
autoload.php
bin
phpunit -> ../phpunit/phpunit/phpunit
templatemap_generator.php -> ../zendframework/zend-
view/bin/templatemap_generator.php
zf-development-mode -> ../zfcampus/zf-development-mode/bin/zf-
development-mode
28
Zend Framework
composer
autoload_classmap.php
autoload_namespaces.php
autoload_psr4.php
autoload_real.php
ClassLoader.php
installed.json
LICENSE
container-interop
container-interop
doctrine
instantiator
myclabs
deep-copy
phpdocumentor
reflection-common
reflection-docblock
type-resolver
phpspec
prophecy
phpunit
php-code-coverage
php-file-iterator
php-text-template
php-timer
php-token-stream
phpunit
phpunit-mock-objects
sebastian
code-unit-reverse-lookup
comparator
diff
environment
exporter
global-state
object-enumerator
29
Zend Framework
recursion-context
resource-operations
version
symfony
yaml
webmozart
assert
zendframework
zend-component-installer
zend-config
zend-console
zend-dom
zend-escaper
zend-eventmanager
zend-http
zend-loader
zend-modulemanager
zend-mvc
zend-router
zend-servicemanager
zend-stdlib
zend-test
zend-uri
zend-validator
zend-view
zfcampus
zf-development-mode
73 directories, 55 files
The Zend Framework application consists of different folders. They are as follows:
Application This directory contains your application. It will house the MVC
system, as well as configurations, services used and your bootstrap file.
Data This directory provides a place to store application data that is volatile and
possibly temporary.
30
Zend Framework
Public This is the applications document root. It starts the Zend application. It
also contains the assets of the application like JavaScript, CSS, Images, etc.
module
Application
config
module.config.php
src
Controller
IndexController.php
Module.php
test
Controller
IndexControllerTest.php
view
application
index
index.phtml
error
404.phtml
index.phtml
layout
layout.phtml
31
Zend Framework
Application This is root directory of the module. The name of the folder will
match the name of the module and the name is also used as the PHP namespace
of all the class defined inside the module. It will house the MVC system, as well as
configurations, services used, and your bootstrap file.
All modules share the same or similar structure as that of the above Application module.
32
10. Zend Framework Creating a Module
Zend Framework
In this chapter, we will learn how to create a MVC based module in the Zend Framework.
Let us create a module called as Tutorial to understand the module creation process.
Write a public function getConfig in the Module class and return the configuration
file for the Tutorial Module.
<?php
namespace Tutorial;
use Zend\ModuleManager\Feature\ConfigProviderInterface;
Configure the Tutorial module in the composer.json under the autoload section by
using the following code.
"autoload": {
"psr-4": {
"Application\\": "module/Application/src/",
"Tutorial\\": "module/Tutorial/src/"
}
}
Update the application using the composer update command as shown below.
composer update
33
Zend Framework
The composer command will do necessary change to the application and show the logs
in the command prompt as shown below:
34
Zend Framework
Create the module configuration file, module.config.php at /config/ with the following
code:
<?php
namespace Tutorial;
use Zend\ServiceManager\Factory\InvokableFactory;
use Zend\Router\Http\Segment;
return [
'controllers' => [
'factories' => [
Controller\TutorialController::class => InvokableFactory::class,
],
],
'view_manager' => [
'template_path_stack' => [
'tutorial' => __DIR__ . '/../view',
],
],
];
The configuration file has three parts and they are as follows:
View configuration Specify the configuration related to view the engine such
as the location of views, etc.
35
Zend Framework
return [
'Zend\Router',
'Zend\Validator',
'Application',
'Tutorial'
];
Run the application by executing the composer serve at the root of the application folder.
We have successfully added a new module, but we still need to add the Controller,
Routing and Views to successfully run the Tutorial module.
36
11. Zend Framework ControllersZend Framework
As discussed earlier, the controller plays an important role in the Zend MVC Framework.
All the webpages in an application needs to be handled by a controller.
use Zend\Stdlib\DispatchableInterface;
use Zend\Stdlib\RequestInterface as Request;
use Zend\Stdlib\ResponseInterface as Response;
The DispatchableInterface is basic and it needs lot of other interfaces to write high level
controllers. Some of such interfaces are as follows:
Keeping these things in mind, the Zend Framework provides lot of readymade controllers
implementing these interfaces. The most important controllers are as explained below.
37
Zend Framework
AbstractActionController
The AbstractActionController (Zend/Mvc/Controller/AbstractActionController) is the most
used controller in the Zend MVC Framework. It has all the necessary features to write a
typical web page. It allows routes (Routing is matching request url to a controller and one
of its methods) to match an action. When matched, a method named after the action will
be called by the controller.
For example, if a route test is matched and the route, test returns hello for action, then
the helloAction method will be invoked.
Return the ViewModel object from indexAction method. The ViewModel object
is used to send data from the controller to view engine, which we will see in the
subsequent chapters.
?php
namespace Tutorial\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
38
Zend Framework
AbstractRestfulController
The AbstractRestfulController (Zend\Mvc\Controller\AbstractRestfulController) inspects
the HTTP method of the incoming request and matches the action (method) by considering
the HTTP methods.
For example, the request with GET HTTP method either matches the getList() method or
the get() method, if the id parameter is found in the request.
AbstractConsoleController
The AbstractConsoleController (Zend\Mvc\Controller\AbstractConsoleController) is like the
AbstractActionController except that it only runs in the console environment instead of a
browser.
39
12. Zend Framework Routing Zend Framework
Routing maps Request URI to a specific controller's method. In this chapter, we will see
how to implement the routes in a Zend Framework.
Hostname segment,
Path segment, and
Query segment.
Routing also checks the host segment, query segment, request HTTP methods, request
HTTP headers, etc., in a certain situation.
namespace Zend\Mvc\Router;
interface RouteInterface
{
public static function factory(array $options = []);
public function match(Request $request);
public function assemble(array $params = [], array $options = []);
}
The main method is match. This match method checks the given request against the
constrain defined in it. If any match is found, it returns the RouteMatch object. This
RouteMatch object provides the details of the matched request as parameters. These
parameters can be extracted from RouteObject using the getParams method.
40
Zend Framework
namespace Zend\Mvc\Router;
class RouteMatch
{
public function __construct(array $params);
public function setMatchedRouteName($name);
public function getMatchedRouteName();
public function setParam($name, $value);
public function getParams();
public function getParam($name, $default = null);
}
In general, a typical MVC application has many routes. Each of this route will be processed
in LIFO order and a single route will be matched and returned. If no route is matched /
returned, then the application returns Page not found error. Zend Framework provides
an interface to process the routes, RouteStackInterface. This RouteStackInterface has
the option to add / remove routes.
namespace Zend\Mvc\Router;
Zend framework provides two implementations of the RouteStack interface and they are
as follows:
SimpleRouteStack
TreeRouteStack
Type of Routes
Zend framework provides a lot of readymade route objects for all the situations under
"Zend\Mvc\Router\Http" namespace. It is enough to select and use proper route object
for the given situation.
41
Zend Framework
Part Used to match the part of the URI path segment using custom logic.
Schema Used to match the URI Schema such as http, https, etc.
Let us see how to write the most commonly used literal and segment Route. Routes are
usually specified in each module's configuration file module.config.php.
Literal Route
Typically, routes are queried in a LIFO order. The Literal route is for doing the exact
matching of the URI path.
$route = Literal::factory(array(
'route' => '/path',
'defaults' => array(
'controller' => 'Application\Controller\IndexController',
'action' => 'index',
),
));
The above route matches the /path in the request url and returns index as the action
and IndexController as controller.
Segment Route
A segmented route is used for whenever your url is supposed to contain variable
parameters.
$route = Segment::factory(array(
'route' => '/:controller[/:action]',
'constraints' => array(
'controller' => '[a-zA-Z][a-zA-Z0-9_-]+',
'action' => '[a-zA-Z][a-zA-Z0-9_-]+',
),
42
Zend Framework
Here, Segments are denoted by a colon and followed by alphanumeric characters. If you
keep a segment is optional then it is enclosed by brackets. Each segment may have
constraints associated with it. Each constraint is a regular expression.
<?php
namespace Tutorial;
use Zend\ServiceManager\Factory\InvokableFactory;
use Zend\Router\Http\Segment;
return [
'controllers' => [
'factories' => [
Controller\TutorialController::class => InvokableFactory::class,
],
],
'router' => [
'routes' => [
'tutorial' => [
'type' => Segment::class,
'options' => [
'route' => '/tutorial[/:action[/:id]]',
'constraints' => [
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
'id' => '[0-9]+',
],
'defaults' => [
43
Zend Framework
We have successfully added the routing for our Tutorial module. We are just one step
behind in completing our Tutorial module. We need to add View for our module, which we
will learn in the subsequent chapter.
44
13. Zend Framework View LayerZend Framework
A View Layer is the presentation layer of the MVC application. It separates the application
logic from the presentation logic. In a typical PHP web application, all business logic and
design are intermixed. Intermixing enables faster development in a small project. But, it
fails miserably in large project, where lot of high level architecture is involved. To change
the design of the web application, a developer needs to work on the business logic as well.
This may be catastrophic resulting in breaking of business logic.
Zend Framework provides a well thought, clean, flexible and extendable View layer. The
View layer is available as a separate module, Zend/View and integrate fine with
Zend/Mvc module. The Zend View Layer is separated into multiple components
interacting nicely with each other.
Renderers - Process data and template from View Model and output a design
representation, maybe the final html output.
Resolvers - Resolves template available in the View Model in such a way that the
Renderer can consume.
The view layer, View processes the ViewModel, resolves the template using a Resolver,
render it using Rendering Strategy and finally outputs it using the Response Renderer.
'view_manager' => [
'template_path_stack' => [
'tutorial' => __DIR__ . '/../view',
],
]
45
Zend Framework
By default, the View layer has a default behavior for all its components. For example, a
ViewModel resolves the template name of a controller's action inside the template root
by lowercase-module-name/lowercase-controller-name/lowercase-action-name rule.
However, this can be overridden by the setTemplate() method of the ViewModel.
Controller
<?php
namespace Tutorial\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
Finally, we have successfully completed the Tutorial module and we can access it using
url http://localhost:8080/tutorial.
46
Zend Framework
return $view;
}
View Helpers
A View Helper is used to write small, atomic functions to be used in templates. Zend
framework provides an interface, Zend\View\Helper\HelperInterface to write standard
view helpers.
47
Zend Framework
namespace Zend\View\Helper;
interface HelperInterface
{
/**
* Set the View object
*
* @param Renderer $view
* @return HelperInterface
*/
public function setView(Renderer $view);
/**
* Get the View object
*
* @return Renderer
*/
public function getView();
}
Built-in Helpers
Zend Framework provides a lot of inbuilt helper function for various purposes. Some of
the View Helpers available in the zend-mvc are as follows:
URL
URL helper is used to generate the URLs matching the routes defined in the application.
48
Zend Framework
For example, in the tutorial module, the route is named as tutorial and it has two
parameters action and id. We can use URL helper to generate two different URLs as shown
below:
<a href="/tutorial/show/10">
Details of Tutorial #10
</a>
Placeholder
Placeholder helper is used to persist content between view scripts and view instances. It
provides option to set data initially and then use it in later stages.
For example, we can set, say company name and then use it in all other places.
A Placeholder provides some of the advanced options to generate complex content from
PHP array and objects. It also has option to capture certain section of the template itself.
For example, the following code captures the template result in between and stores it in
the productlist placeholder.
Class Product:
class Product
{
public $name;
49
Zend Framework
public $description;
}
Controller:
$p1->description = 'Car';
Template:
Result:
<div class="foo">
<h2>Car</h2>
<p>Car</p>
</div>
50
Zend Framework
<div class="foo">
<h2>Cycle</h2>
<p>Cycle</p>
</div>
Doctype
The Doctype helper is used to generate various html doctypes. It is concrete
implementation of the Placeholder helper. The doctype can be set in a bootstrap file and
config file.
use Zend\View\Helper\Doctype;
Module Configuration:
// module/Application/config/module.config.php:
return [
/* ... */
'view_manager' => [
'doctype' => 'html5',
/* ... */
],
];
Template:
HeadTitle
The HeadTitle helper is used to generate the html title element. It is the concrete
implementation of Placeholder helper. Zend provides an option to set the title in the
module configuration file and it can be set at any level like site, module, controller, action,
etc. A partial code for the HeadTitle is as follows:
51
Zend Framework
Module:
headTitleHelper->append($action);
$headTitleHelper->append($controller);
$headTitleHelper->append($module);
$headTitleHelper->append($siteName);
Template:
Result:
HeadMeta
The HeadMeta helper is used to generate html meta tags. It is a concrete implementation
of the Placeholder helper.
Template:
<?php
$this->headMeta()->appendName('keywords', 'turorialspoint, zend framework,
php');
echo $this->headMeta()
?>
Result:
HeadLink
The HeadLink helper is used to generate html links to include external resources. It is
concrete implementation of the Placeholder helper.
Template:
<?php
// setting links in a view script:
$this->headLink(['rel' => 'icon', 'href' => '/img/favicon.ico'], 'PREPEND')
->appendStylesheet('/styles/site.css')
->prependStylesheet(
'/styles/mystyle.css',
52
Zend Framework
'screen',
true,
['id' => 'mystyle']
);
Result:
HeadStyle
The HeadStyle helper is used to generate inline CSS styles. It is concrete implementation
of the Placeholder helper.
Template
HeadScript
The HeadScript is used to generate inline script or to include external scripts. It is concrete
implementation of the Placeholder helper.
Template
<? $this->headScript()->appendFile(/js/sample.js);?>
InlineScript
The InlineScript is used to generate a script in both head and body section of the html
template. It is derived from the HeadScript.
53
Zend Framework
HTMLList
The HTMLList is used to generate ordered and unordered list. The definition of the HTMLList
is as follows:
Definition:
Template:
$items = [
'2015',
[
'March',
'November'
],
'2016',
];
echo $this->htmlList($items);
Result:
<ul>
<li>2015
<ul>
<li>March</li>
<li>November</li>
</ul>
</li>
<li>2016</li>
</ul>
Cycle
A Cycle is used to generate alternatives in a loop environment. It has assign, next and
prev function.
Controller:
54
Zend Framework
Template:
<table>
Result:
<table>
<tr style="background-color: #F0F0F0">
<td>One</td>
</tr>
<tr style="background-color: #FFF">
<td>Two</td>
</tr>
</table>
BasePath The BasePath is used to generate path of the public folder of the
application's root.
Partial Partial is used to render a specific template in its own variable scope.
Identity Identity is used to retrieve the logged-in user's identity from the
Authentication Service.
JSON JSON is used in a restful environment, where the output is in JSON format.
It emits proper HTTP header and disables the layout concept.
There are still lot of helpers available in Zend Framework such as the i18n helper, form
helpers, pagination helpers, navigation helpers, etc.
55
Zend Framework
<?php
namespace Tutorial\View\Helper;
use Zend\View\Helper\AbstractHelper;
'view_helpers' => [
'aliases' => [
'testHelper' => View\Helper\TestHelper::class,
],
'factories' => [
View\Helper\TestHelper::class => InvokableFactory::class,
],
56
Zend Framework
],
57
14. Zend Framework Layout Zend Framework
A Layout represents the common parts of multiple views i.e. for example, page header
and footer. By default, layouts should be stored in the view/layout folder.
Here, the template_map is used to specify the layout. If layout is not found, then it will
return an error. Let us have a look at the main layout of the skeleton application.
Layout.phtml
<?= $this->doctype() ?>
<html lang="en">
<head>
<meta charset="utf-8">
<?= $this->headTitle('ZF Skeleton Application')->setSeparator(' - ')-
>setAutoEscape(false) ?>
58
Zend Framework
<?= $this->headMeta()
->appendName('viewport', 'width=device-width, initial-scale=1.0')
->appendHttpEquiv('X-UA-Compatible', 'IE=edge')
?>
59
Zend Framework
As you analyze the layout, it mostly uses the view helpers, which we discussed in the
previous chapter. As we look closer, the layout uses a special variable, $this->content.
This variable is important as it will be replaced by the view script (template) of the actual
requested page.
To begin with, let us create a tutorial.css file under the public/css directory.
body {
background-color: lightblue;
}
h1 {
color: white;
text-align: center;
}
60
Zend Framework
Add a new about link in the navigation section using the URL helper.
This layout page is common for the tutorial module application. Update the
view_manager section of the tutorial module configuration file.
<h2>About page</h2>
61
15. Zend Framework Models & Database
Zend Framework
In this chapter, we will discuss regarding the various models and the database of the Zend
Framework.
Controllers communicate with models and ask them to retrieve information they
need. This retrieved information is then passed by the controller to the View.
Finally, View will render the model as user consumable presentational data.
It is very rare that a model directly interacts with a view, but sometimes it may
happen.
Models can talk with each other and aren't self-contained. They have relationships
with each other. These relationships make it easier and quicker for a controller to
get information, since it doesn't have to interact with different models; the models
can do that themselves.
<?php
namespace Tutorial\Model;
class Book
{
public $id;
public $author;
public $title;
}
Let us see how to connect the MySqlservice via PHP's PDO driver in Zend framework
through the following steps.
62
Zend Framework
use tutorials;
INSERT INTO book (author, title) VALUES ('Dennis Ritchie', 'C Programming');
INSERT INTO book (author, title) VALUES ('James gosling', 'Java Programming');
INSERT INTO book (author, title) VALUES ('Rasmus Lerdorf', 'Programming PHP');
<?php
return array(
'db' => array(
'driver' => 'Pdo',
'dsn' => 'mysql:dbname=tutorials;host=localhost',
'driver_options' => array(
63
Zend Framework
'Zend\Db\Adapter\Adapter' =>
'Zend\Db\Adapter\AdapterServiceFactory',
),
),
);
<?php
return array(
'db' => array(
'username' => '<user_name>',
'password' => '<password>',
),
);
<?php
namespace Tutorial\Model;
class Book
{
public $id;
public $author;
public $title;
64
Zend Framework
<?php
namespace Tutorial\Model;
class Book
{
public $id;
public $author;
public $title;
<?php
namespace Tutorial\Model;
use Zend\Db\TableGateway\TableGatewayInterface;
class BookTable
65
Zend Framework
{
protected $tableGateway;
public function __construct(TableGatewayInterface $tableGateway)
{
$this->tableGateway = $tableGateway;
}
{
$resultSet = $this->tableGateway->select();
return $resultSet;
}
}
We have used select() method of the TableGateway class to fetch the book information
from the database. But, we have not used any reference to the table book in the code.
The TableGateway is generic in nature and it can fetch data from any table by using certain
configuration. Usually, these configurations are done in the module.config.php file,
which we will discuss in the subsequent steps.
<?php
namespace Tutorial;
use Zend\Db\Adapter\AdapterInterface;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;
use Zend\ModuleManager\Feature\ConfigProviderInterface;
66
Zend Framework
$tableGateway = $container-
>get(Model\BookTableGateway::class);
$table = new Model\BookTable($tableGateway);
return $table;
},
Model\BookTableGateway::class => function ($container) {
$dbAdapter = $container->get(AdapterInterface::class);
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Model\Book());
Here, we have registered the BookTable class using the service manager. The BookTable
class is used to fetch the book information and by registering it, we can access it wherever
needed. Since, the registered services are shared, they increase performance, reduce the
memory consumption, etc.
67
Zend Framework
This Constructor dependency helps to get the BookTable service while the controller itself
is in the initialization stage. Update the controller section of the tutorial module
configuration, module.config.php as shown below.
'controllers' => [
'factories' => [
Controller\TutorialController::class => function($container) {
return new Controller\TutorialController(
$container->get(Model\BookTable::class)
);
},
],
],
private $table;
Fetch book information using the BookTable's fetchAll() method and register it
into the view.
68
Zend Framework
return $view;
}
<table class="table">
<tr>
<th>Author</th>
<th>Title</th>
<th> </th>
</tr>
<?php foreach ($data as $sampledata) : ?>
<tr>
<td><?php echo $this->escapeHtml($data->author);?></td>
69
16. Zend Framework Different Databases
Zend Framework
As discussed in the last chapter, Zend framework provides a generic way to access the
database using the Database Driver concept. Working with a database solely depends
on the driver information and so, connecting with different database involves just changing
the driver information.
Let us now change the book example to connect to the postgresql database with the
following steps.
Step 1: Create a database, tutorials in the local postgresql database using the following
command:
Step 2: Add book table. Move to the new database and execute the table creation script.
\c tutorials
CREATE TABLE book (
id SERIAL NOT NULL,
author varchar(100) NOT NULL,
title varchar(100) NOT NULL,
PRIMARY KEY (id)
);
INSERT INTO book (author, title) VALUES ('Dennis Ritchie', 'C Programming');
INSERT INTO book (author, title) VALUES ('James gosling', 'Java Programming');
INSERT INTO book (author, title) VALUES ('Rasmus Lerdorf', 'Programming PHP');
<?php
return array(
'db' => array(
'driver' => 'Pdo',
'dsn' => 'pgsql:dbname=tutorials;host=localhost',
'driver_options' => array(
),
),
);
70
Zend Framework
return array(
'db' => array(
'username' => '<username>',
'password' => '<password>',
),
);
71
17. Zend Framework Forms & Validation
Zend Framework
A Zend form framework has three subcomponents to manage the forms. They are as
explained below in detail:
Elements Used to define a single html input control mapped to a property in the
model.
Form Used to create an html form and consists of elements and fieldsets.
Example
Let us now create a simple form to add book into the database. To do this, we should
adhere to the following steps:
<?php
namespace Tutorial\Form;
use Zend\Form\Form;
72
Zend Framework
{
public function __construct($name = null)
{
parent::__construct('book');
$this->add(array(
'name' => 'id',
'type' => 'Hidden',
));
$this->add(array(
'name' => 'author',
'type' => 'Text',
'options' => array(
'label' => 'Author',
),
));
$this->add(array(
'name' => 'title',
'type' => 'Text',
'options' => array(
'label' => 'Title',
),
));
$this->add(array(
'name' => 'submit',
'type' => 'Submit',
'attributes' => array(
'value' => 'Go',
'id' => 'submitbutton',
),
));
}
}
73
Zend Framework
The Form class provides an add method to map the model and its corresponding form
details. we have created the BookForm by extending the Form class and added the form
details for Book model.
<?php
namespace Tutorial\Model;
use Zend\InputFilter\InputFilterInterface;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilter;
protected $inputFilter;
74
Zend Framework
));
$inputFilter->add(array(
'name' => 'author',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 1,
'max' => 100,
),
),
),
));
$inputFilter->add(array(
'name' => 'title',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 1,
'max' => 100,
),
),
75
Zend Framework
),
));
$this->inputFilter = $inputFilter;
}
return $this->inputFilter;
}
The getInputFilter is used to get the validation details of the model. Zend framework
provides a rich set of filters and validators to validate the form. Some of the filters and
validators used in the book model are as follows:
StringLength validator Ensure that the user does not enter more characters
than the specified limit.
BookTable.php
<?php
namespace Tutorial\Model;
use Zend\Db\TableGateway\TableGatewayInterface;
class BookTable
76
Zend Framework
protected $tableGateway;
public function __construct(TableGatewayInterface $tableGateway)
{
$this->tableGateway = $tableGateway;
}
77
Zend Framework
if ($this->getBook($id)) {
$this->tableGateway->update($data, array('id' => $id));
} else {
throw new \Exception('Book id does not exist');
}
}
}
}
$request = $this->getRequest();
if ($request->isPost()) {
$book = new Book();
$form->setInputFilter($book->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$book->exchangeArray($form->getData());
$this->bookTable->saveBook($book);
78
Zend Framework
If request's http method is not post, it just renders the template, add.phtml
If the request's http method is not post, then it sets the inputfilter, gets the
request data and sets it into the inputfiler.
Checks whether the form is valid using the isValid() method of Form class.
If the form is valid, it saves the book into the database and redirects to the home
page.
Add.phtml
<?php
?>
<?php
if(!empty($form))
{
echo $this->form()->openTag($form);
echo $this->formHidden($form->get('id'));
echo $this->formRow($form->get('author'))."<br>";
echo $this->formRow($form->get('title'))."<br>";
echo $this->formSubmit($form->get('submit'));
79
Zend Framework
echo $this->form()->closeTag();
}
Here, we are rendering the book form using the Form instance, $form.
Form Page
80
18. Zend Framework File Uploading
Zend Framework
File uploading is one of the main concept in form programming. Zend framework provides
all the necessary items to upload files through the zend-form and the zend-inputfilter
component.
FileInput Class
The zend-inputfilter component provides Zend\InputFilter\FileInput class to handle the
html file input element <input type='file' />. The FileInput is like the other input
filters with a few exceptions. They are as follows:
Since PHP saves the uploaded file details in $_FILES global array, the FileInput
gathers the uploaded file information through $_FILES only.
Validation needs to be done before the FileInput class processes the data. It is the
opposite behavior of the other input filters.
To add a file upload type in a form, we need to use input type File. The partial code is as
follows:
$form->add(array(
'name' => 'imagepath',
'type' => 'File',
'options' => array(
'label' => 'Picture',
),
));
81
Zend Framework
$inputFilter->add($file);
ALTER TABLE `book` ADD `imagepath` VARCHAR(255) NOT NULL AFTER 'imagepath';
Update BookForm.php
Add the file input element to upload a picture in the book form
myapp/module/Tutorial/src/Model/BookForm.php.
$this->add(array(
'name' => 'imagepath',
'type' => 'File',
'options' => array(
'label' => 'Picture',
),
));
Update Book.php
Do the following changes in the Book class myapp/module/Tutorial/src/Model/Book.php.
public $imagepath;
82
Zend Framework
array(1) {
["imagepath"] => array(5) {
["name"] => string "myimage.png"
["type"] => string "image/png"
["tmp_name"] => string
"public/tmpuploads/file_<random_string>.<image_ext>"
["error"] => int <error_number>
["size"] => int <size>
}
}
If the imagepath comes from a database, it will be a simple string. The partial code
listing to parse an imagepath is as follows:
if(!empty($data['imagepath']))
{
if(is_array($data['imagepath']))
{
$this->imagepath = str_replace("./public", "",
$data['imagepath']['tmp_name']);
83
Zend Framework
}
else
{
$this->imagepath = $data['imagepath'];
}
}
else
{
$data['imagepath'] = null;
}
<?php
namespace Tutorial\Model;
use Zend\InputFilter\InputFilterInterface;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\Filter\File\RenameUpload;
use Zend\Validator\File\UploadFile;
use Zend\InputFilter\FileInput;
use Zend\InputFilter\InputFilter;
protected $inputFilter;
84
Zend Framework
{
if (!$this->inputFilter) {
$inputFilter = new InputFilter();
$inputFilter->add(array(
'name' => 'id',
'required' => true,
'filters' => array(
array('name' => 'Int'),
),
));
$inputFilter->add(array(
'name' => 'author',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 1,
'max' => 100,
),
),
),
));
$inputFilter->add(array(
'name' => 'title',
'required' => true,
'filters' => array(
85
Zend Framework
$this->inputFilter = $inputFilter;
}
return $this->inputFilter;
}
86
Zend Framework
if(!empty($data['imagepath']))
{
if(is_array($data['imagepath']))
{
$this->imagepath = str_replace("./public", "",
$data['imagepath']['tmp_name']);
}
else
{
$this->imagepath = $data['imagepath'];
}
}
else
{
$data['imagepath'] = null;
}
}
}
Update BookTable.php
We have updated BookForm and the Book model. Now, we update the BookTable and
modify the saveBook method. This is enough to include the imagepath entry in the data
array, $data.
$data = array (
'author' => $book->author,
'title' => $book->title,
'imagepath' => $book->imagepath
);
87
Zend Framework
<?php
namespace Tutorial\Model;
use Zend\Db\TableGateway\TableGatewayInterface;
class BookTable
{
protected $tableGateway;
public function __construct(TableGatewayInterface $tableGateway)
{
$this->tableGateway = $tableGateway;
}
88
Zend Framework
$post = array_merge_recursive(
$request->getPost()->toArray(),
$request->getFiles()->toArray()
);
$request = $this->getRequest();
if ($request->isPost()) {
$book = new Book();
$form->setInputFilter($book->getInputFilter());
89
Zend Framework
$post = array_merge_recursive(
$request->getPost()->toArray(),
$request->getFiles()->toArray()
);
$form->setData($post);
if ($form->isValid()) {
$book->exchangeArray($form->getData());
$this->bookTable->saveBook($book);
echo $this->formRow($form->get('imagepath'))."<br>";
<?php
90
Zend Framework
<?php
if(!empty($form))
{
echo $this->form()->openTag($form);
echo $this->formHidden($form->get('id'));
echo $this->formRow($form->get('author'))."<br>";
echo $this->formRow($form->get('title'))."<br>";
echo $this->formRow($form->get('imagepath'))."<br>";
echo $this->formSubmit($form->get('submit'));
echo $this->form()->closeTag();
}
Form Page
Index Page
91
Zend Framework
92
19. Zend Framework AJAX Zend Framework
AJAX is a modern technology in web programming. It provides options to send and receive
data in a webpage asynchronously, without refreshing the page. Zend framework provides
an option to work with the json model through zend-view and zend-json component.
Let us learn the Zend AJAX programming in this chapter.
Concept
Zend framework provides two methods to easily write an AJAX enabled web application.
They are as follows:
if ($request->isXmlHttpRequest()) {
// Ajax request
} else {
// Normal request
}
93
Zend Framework
'view_manager' => [
'template_map' => array('layout/layout' => __DIR__ .
'/../view/layout/newlayout.phtml'),
'template_path_stack' => [
'tutorial' => __DIR__ . '/../view',
],
'strategies' => array(
'ViewJsonStrategy',
),
],
if ($request->isXmlHttpRequest() || $query->get('showJson') == 1) {
$jsonData = array();
$idx = 0;
foreach($data as $sampledata)
{
$temp = array(
'author' => $sampledata->author,
'title' => $sampledata->title,
'imagepath' => $sampledata->imagepath
);
$jsonData[$idx++] = $temp;
}
94
Zend Framework
else
{
$view = new ViewModel();
}
return $view;
}
Here, ajaxAction will check whether the incoming request is AJAX or not. If the incoming
request is AJAX, then the JsonModel will be created. Otherwise, a normal ViewModel
will be created.
In both cases, the book information will be fetched from database and populated in the
model. If the model is a JsonModel, then JsonStrategy will be invoked and it will encode
the data as json and return as response.
Clicking that link will do an AJAX request, which will fetch the book information as Json
data and shows the book information as a formatted table. The AJAX processing is done
using the JQuery.
<script language="javascript">
$(document).ready(function(){
$("#loadbook").on("click", function(event){
$.ajax({
95
Zend Framework
url: '/tutorial/ajax',
type: 'POST',
dataType: 'json',
async: true,
success: function(data, status) {
var e = $('<tr><th>Author</th><th>Title</th><th>Picture</th></tr>');
$('#book').html('');
$('#book').append(e);
for(i = 0; i < data.length; i++)
{
book = data[i];
var e = $('<tr><td id="author"></td><td id="title"></td><td
id="imagepath"><img src=""/></td></tr>');
$('#author', e).html(book['author']);
$('#title', e).html(book['title']);
$('#imagepath img', e).attr('src', book['imagepath']);
$('#book').append(e);
}
},
error : function(xhr, textStatus, errorThrown) {
alert('Ajax request failed.');
}
});
});
});
</script>
96
Zend Framework
Ajax Page:
97
Zend Framework
98
20. Zend Framework Cookie Management
Zend Framework
The Cookie is a very important concept in a web application. It provides the option to
persist the user's data, usually a small piece of information in the browser itself for a
limited period.
A Cookie is used to maintain the state of the web application. Zend framework provides a
cookie module inside the zend-http component. This zend-http provides the HTTP
abstraction and its implementation.
Concept
The zend-http provides the Zend\Http\Cookies class to manage cookies. It is used along
with the Zend\Http\Client class, which is used to send a request to a web server.
Cookies can be initialized as shown in the code below:
use Zend\Http\Cookies
$c = new Cookies();
When the HTTP client (Zend\Http\Client) first sends a URI request to the web server, it
does not have any cookie. Once the request is received by the web server, it includes the
cookie in its response object as the HTTP Header, Set-Cookie and sends it to the HTTP
client. The HTTP client will extract the cookie from the http response and resent it as same
HTTP Header in the subsequent request. Generally, each cookie will be mapped to a
domain and a path of the domain.
addCookie(uri) It is used to add a cookie into the request object of the given
URI.
99
Zend Framework
isEmpty() It is used to find whether the given Cookie object has any cookie or
not.
In the next chapter, we will discuss regarding session management in the Zend
Framework.
100
21. Zend Framework Session Management
Zend Framework
A Session is a very important concept in a web application. It provides the option to persist
the user's data in the web server for a limited period of time. Zend framework provides a
separate component, zend-session to handle the session information.
Session Components
Zend framework provides six components to handle session management. All these
components have been explained below:
The default configuration is enough to work with a session. Using the above components,
all aspects of a session can be handled easily.
101
Zend Framework
$c = new Container();
Check whether an arbitrary key count exists. If the key is not available, initialize
the count with value 1. If it is available, increment the value as shown in the
following code.
if (!isset($c->count)) {
$c->count = 0;
} else {
$c->count++;
}
Refreshing the page will increase the value of count in the session. The complete
listing is as follows:
TutorialController.php
if (!isset($c->count)) {
$c->count = 0;
} else {
$c->count++;
}
return $view;
}
102
Zend Framework
session.pthml
Sample Result:
103
22. Zend Framework Authentication
Zend Framework
Authentication is one of the most significant and must-have feature in any web application.
Zend Framework provides a separate component to handle authentication, which is called
as the zend-authentication.
Concept
Usually, a developer writes a php function to authenticate the user details against a
datasource. Once the authentication is done, the authentication details are persisted for
subsequent requests. Zend Framework generalizes this concept and provides two classes,
which are explained below:
Class 1: Zend\Authentication\Adaptor\AdaptorInterface
This class provides a single method, authenticate to write the authentication logic. The
authenticate method returns an instance of Zend\Authentication\Result class.
This Result object holds the authentication status; identity if the authentication succeeds
and an error message, if the authentication fails. The signature of the authenticate
interface and result class is as follows:
AdaptorInterface:
namespace Zend\Authentication\Adaptor;
public function authenticate()
{
// code
}
Result class:
namespace Zend\Authentication;
class Result
{
public function __construct($code, $identity, array $messages = []);
}
104
Zend Framework
Class 2: Zend\Authentication\AuthenticationService
The AuthenticationService is the main component, which uses the already configured
adaptor for authentication purposes. Once the authentication is done, it persists the
authentication details and provides methods, hasIdentity() to check whether an identity
is available, getIdentity() to get the authentication details and clearIdentity() to clear
the authentication details.
if($result->isValid) {
$identity = $auth->getIdentity();
} else {
// process $result->getMessages()
}
// clear
$auth->clearIdentity();
The stuff related to authorization are packaged as two separate modules, which are
zend-permissions-acl and zend-permissions-rbac. The zend-permissions-acl is based
on the Access control list and the zend-permissions-rbac is based on the role based access
control list. They provide high-level abstraction of ACL & RBAC concept and aids in writing
the enterprise grade application.
105
23. Zend Framework Email Management
Zend Framework
The Zend Framework provides a separate component called as zend-mail to send email
messages. The zend-mail component also provides an option to read and write email
messages with attachments both in text and html format. Sending an email in Zend is
much easier and simple to configure.
Let us go through the email concepts, basic settings, advanced settings such as SMTP
transport, etc., in this chapter.
use Zend\Mail;
Zend provides Zend\Mail\Sendmail class to send the mail message. Sendmail uses the
php native mail function, mail to send the mail message and we can configure the
transport layer using php configuration file.
The zend-mail provides many transport layer and each may require many additional
parameters such as username, password, etc.
106
Zend Framework
isValid() : bool
getEncoding() : string
getHeaders() : Zend\Mail\Headers
setFrom(
string|AddressInterface|array|AddressList|Traversable
$emailOrAddressList,
string|null $name
) : void
addFrom(
string|AddressInterface|array|AddressList|Traversable
$emailOrAddressOrList,
string|null $name
) : void
107
Zend Framework
getFrom() : AddressList
setTo - Overwrite the address list in the To recipients.
setTo(
string|AddressInterface|array|AddressList|Traversable
$emailOrAddressList,
null|string $name
) : void
Here,
108
Zend Framework
Create the SMTP transport layer and add the necessary configuration.
$transport->send($message);
109
Zend Framework
<?php
use Zend\Mail\Message;
use Zend\Mail\Transport\Smtp as SmtpTransport;
use Zend\Mail\Transport\SmtpOptions;
Now, run the application in the command prompt php Mail.php. This will send the mail
as configured in the application.
110
24. Zend Framework Unit Testing
Zend Framework
In general, we can debug a PHP application by using the advanced debugger tool or by
using simple commands like echo and die. In a web scenario, we need to test the business
logics as well as the presentation layer. Forms in a web application can be tested by
entering relevant test data to ensure that the forms are working as expected.
The design of a website can be tested manually by using a browser. These type of test
processes can be automated using unit testing. A unit test is essential in large projects.
These unit tests will help to automate the testing process and alert the developer when
something goes wrong.
After executing the above command, you will get a response as shown in the following
code block.
Now, when you open the composer.json file, you will see the following changes:
"require-dev": {
"phpunit/phpunit": "^5.7"
}
111
Zend Framework
CSS Select Assertions Used to check the response HTML using the HTML DOM
model.
Response Header Assertions Used to check the response header like status
code (assertResponseStatusCode)
For example, to write a test for the TutorialController available under the Tutorial module,
the test class needs to be placed under myapp/module/Tutorial/test/Controller/ directory.
Example
Let us write a test class to unit test the TutorialController.
To begin with, we should write a class called TutorialControllerTest and extend it to the
AbstractHttpControllerTestCase.
The next step is to write a Setup method to setup the test environment. This can be done
by calling the setApplicationConfig method and passing our main application config file
myapp/config/application.config.php
$this->setApplicationConfig(ArrayUtils::merge(
include __DIR__ . '/../../../../config/application.config.php',
$configOverrides
));
parent::setUp();
}
112
Zend Framework
Write one or more methods and call various assert methods depending on the requirement.
$this->assertMatchedRouteName('tutorial');
We have written the test class and the complete listing is as follows:
<?php
namespace TutorialTest\Controller;
use Tutorial\Controller\TutorialController;
use Zend\Stdlib\ArrayUtils;
use Zend\Test\PHPUnit\Controller\AbstractHttpControllerTestCase;
$this->setApplicationConfig(ArrayUtils::merge(
include __DIR__ . '/../../../../config/application.config.php',
$configOverrides
));
parent::setUp();
}
113
Zend Framework
Now, open a command prompt, move on to application root directory and execute the
phpunit executable available inside the vendor folder.
cd /path/to/app
./vendor/bin/phpunit ./vendor/bin/phpunit
module/Tutorial/test/Controller/TutorialControllerTest.php
. 1 / 1
(100%)
OK (1 test, 5 assertions)
114
25. Zend Framework Error Handling
Zend Framework
Failure of system needs to be handled effectively for the smooth running of the system.
Zend Framework comes with a default error trapping that prints and logs the error as
they occur. This same error handler is used to catch Exceptions.
The Error Handler displays errors when the debug is true and logs the error when the
debug is false. Zend Framework has several exception classes and the built-in exception
handling will capture any uncaught exception and render a useful page.
'view_manager' => [
'display_not_found_reason' => true,
'display_exceptions' => true,
'doctype' => 'HTML5',
'not_found_template' => 'error/404',
'exception_template' => 'error/index',
'template_map' => [
'layout/layout' => __DIR__ . '/../view/layout/layout.phtml',
'application/index/index' => __DIR__ .
'/../view/application/index/index.phtml',
'error/404' => __DIR__ . '/../view/error/404.phtml',
'error/index' => __DIR__ . '/../view/error/index.phtml',
],
'template_path_stack' => [
__DIR__ . '/../view',
],
],
The most important item among these is the error/index. This is the template shown
when an exception occurs in the system. We can modify this template,
myapp/module/Application/view/error/index.phtml to control the amount of error to be
shown.
115
26. Zend Framework Working Example
Zend Framework
In this chapter, we will learn how to create a complete MVC based Employee Application
in Zend Framework. Follow the steps given below.
Step 1: Module.php
First, we should create an Employee module inside the myapp/module/Employee/src/
directory and then implement the ConfigProviderInterface interface.
<?php
namespace Employee;
use Zend\ModuleManager\Feature\ConfigProviderInterface;
Step 2: composer.json
Configure the Tutorial module in composer.json under the autoload section by using
the following code.
"autoload": {
"psr-4": {
"Application\\": "module/Application/src/",
"Tutorial\\": "module/Tutorial/src/",
"Employee\\": "module/Employee/src/"
}
}
116
Zend Framework
composer update
The Composer command will do the necessary changes to the application and show the
logs as shown in the command prompt below.
117
Zend Framework
Downloading: 100%
<?php
namespace Employee;
use Zend\ServiceManager\Factory\InvokableFactory;
use Zend\Router\Http\Segment;
return [
'controllers' => [
'factories' => [
Controller\EmployeeController::class => InvokableFactory::class,
],
],
'view_manager' => [
'template_path_stack' => [
'employee' => __DIR__ . '/../view',
],
],
];
118
Zend Framework
Now, configure the Employee module in the application level configuration file
myapp/config/modules.config.php.
return [
'Zend\Router',
'Zend\Validator',
'Application',
'Tutorial',
'Employee'
];
Step 4: EmployeeController
Create a new PHP class, EmployeeController by extending the AbstractActionController
and place it at the myapp/module/Employee/src/Controller directory.
<?php
namespace Employee\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
<?php
namespace Employee;
119
Zend Framework
use Zend\ServiceManager\Factory\InvokableFactory;
use Zend\Router\Http\Segment;
return [
'controllers' => [
'factories' => [
Controller\EmployeeController::class => InvokableFactory::class,
],
],
'router' => [
'routes' => [
'employee' => [
'type' => Segment::class,
'options' => [
'route' => '/employee[/:action[/:id]]',
'constraints' => [
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
'id' => '[0-9]+',
],
'defaults' => [
'controller' => Controller\EmployeeController::class,
'action' => 'index',
],
],
],
],
],
'view_manager' => [
'template_path_stack' => [
'employee' => __DIR__ . '/../view',
],
],
];
We have successfully added the routing for our Employee module. The next step is to
create a view script for the Employee application.
120
Zend Framework
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
Finally, we have successfully completed the Employee module. we can access it using the
following url http://localhost:8080/employee.
Result:
121
Zend Framework
In the next step, we will perform add, edit and delete data operations in the employee
application. To perform these operations, we should first create a database model. It is
described in the next step.
<?php
namespace Employee\Model;
class Employee
{
public $id;
public $emp_name;
public $emp_job;
}
Let us create a table named as employee in the database using following SQL command:
use tutorials;
122
Zend Framework
Insert data into the employee table using the following query:
return
[
'db' =>
[
'driver' => 'Pdo',
'dsn' => 'mysql:dbname=tutorials;host=localhost',
'driver_options' => [
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
],
],
];
<?php
return array(
'db' => array(
'username' => '<user_name>',
'password' => '<password>',
),
);
123
Zend Framework
<?php
namespace Employee\Model;
class Employee
{
public $id;
public $emp_name;
public $emp_job;
<?php
namespace Employee\Model;
use Zend\Db\TableGateway\TableGatewayInterface;
class EmployeeTable
{
protected $tableGateway;
public function __construct(TableGatewayInterface $tableGateway)
{
$this->tableGateway = $tableGateway;
}
124
Zend Framework
return $resultSet;
}
}
<?php
namespace Employee;
use Zend\Db\Adapter\AdapterInterface;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;
use Zend\ModuleManager\Feature\ConfigProviderInterface;
125
Zend Framework
},
'controllers' => [
'factories' => [
Controller\EmployeeController::class => function($container) {
return new Controller\EmployeeController(
$container->get(Model\EmployeeTable::class)
);
},
],
],
<?php
namespace Employee\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
126
Zend Framework
use Employee\Model\Employee;
use Employee\Model\EmployeeTable;
return $view;
}
}
<?php
$title = 'Employee application';
$this->headTitle($title);
?>
<table class="table">
<tr>
<th>Employee Name</th>
<th>Employee Job </th>
<th>Edit/Delete operations</th>
127
Zend Framework
</tr>
<?php foreach ($data as $empdata) : ?>
<tr>
Now we have successfully created a database model and can fetch the records within the
application.
Result:
The next step explains about the insert, edit and delete data operations in the employee
module.
128
Zend Framework
<?php
namespace Employee\Form;
use Zend\Form\Form;
$this->add(array(
'name' => 'id',
'type' => 'Hidden',
));
$this->add(array(
'name' => 'emp_name',
'type' => 'Text',
'options' => array(
'label' => 'Name',
),
));
$this->add(array(
'name' => 'emp_job',
'type' => 'Text',
'options' => array(
'label' => 'Job',
),
));
$this->add(array(
'name' => 'submit',
'type' => 'Submit',
'attributes' => array(
129
Zend Framework
<?php
namespace Employee\Model;
130
Zend Framework
$inputFilter->add(array(
'name' => 'id',
'required' => true,
'filters' => array(
array('name' => 'Int'),
),
));
$inputFilter->add(array(
'name' => 'emp_name',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 1,
'max' => 50,
),
),
),
));
131
Zend Framework
$inputFilter->add(array(
'name' => 'emp_job',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
$this->inputFilter = $inputFilter;
}
return $this->inputFilter;
}
}
<?php
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Employee\Model\Employee;
use Employee\Model\EmployeeTable;
use Employee\Form\EmployeeForm;
132
Zend Framework
$form->get('submit')->setValue('Add');
$request = $this->getRequest();
if ($request->isPost()) {
$employee = new Employee();
$form->setInputFilter($employee->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$employee->exchangeArray($form->getData());
$this->table->saveEmployee($employee);
if (!$row) {
throw new \Exception("Could not find row $id");
}
133
Zend Framework
return $row;
}
<?php
$title = 'Add new employee';
$this->headTitle($title);
?>
<h1><?php echo $this->escapeHtml($title); ?></h1>
<?php
$form->setAttribute('action', $this->url('employee', array('action' =>
'add')));
$form->prepare();
134
Zend Framework
echo $this->form()->openTag($form);
echo $this->formHidden($form->get('id'));
echo $this->formRow($form->get('emp_name'))."<br>";
echo $this->formRow($form->get('emp_job'))."<br>";
echo $this->formSubmit($form->get('submit'));
echo $this->form()->closeTag();
Request the application using the url, http://localhost:8080/employee/add
Result:
Once the data has been added, it will redirect to the home page.
135
Zend Framework
try {
$employee = $this->table->getEmployee($id);
}
catch (\Exception $ex) {
return $this->redirect()->toRoute('employee', array(
'action' => 'index'
));
}
$request = $this->getRequest();
if ($request->isPost()) {
$form->setInputFilter($employee->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$this->table->saveEmployee($employee);
return array(
136
Zend Framework
Here, we look for the id, which is in the matched route and then load the employee details
for the editing operation.
In which, the exchangeArray() is used for iteration. This function is used for binding the
data from the employee table.
<?php
$title = 'Edit employee records';
$this->headTitle($title);
?>
<?php
$form = $this->form;
$form->setAttribute('action', $this->url(
'employee',
array(
'action' => 'edit',
137
Zend Framework
echo $this->form()->openTag($form);
echo $this->formHidden($form->get('id'));
echo $this->formRow($form->get('emp_name'))."<br>";
echo $this->formRow($form->get('emp_job'))."<br>";
echo $this->formSubmit($form->get('submit'));
echo $this->form()->closeTag();
Once the data has been edited, it will redirect to the home page.
138
Zend Framework
$request = $this->getRequest();
if ($request->isPost()) {
$del = $request->getPost('del', 'No');
if ($del == 'Yes') {
$id = (int) $request->getPost('id');
139
Zend Framework
$this->table->deleteEmployee($id);
}
return $this->redirect()->toRoute('employee');
}
return array(
'id' => $id,
'employee' => $this->table->getEmployee($id)
);
}
Here, the deleteEmployee() method deletes the employee by his id and redirects to the
employees list page (home page).
Let us now create a corresponding view scripts for the deleteAction() method.
<?php
$title = 'Delete an employee record';
$this->headTitle($title);
?>
<h1><?php echo $this->escapeHtml($title); ?></h1>
<?php
$url = $this->url('employee', array(
'action' => 'delete',
'id' => $this->id,
));
?>
140
Zend Framework
<div>
<input type="hidden" name="id" value="<?php echo (int) $employee->id; ?>" />
<input type="submit" name="del" value="Yes" />
<input type="submit" name="del" value="No" />
</div>
</form>
Now, delete any employee using the edit link in the home page and the result will be as
shown in the following screenshot.
Result:
Conclusion: In the current competitive environment, Zend framework is placed at the top
spot by the developer. It provides abstractions to any program or any type of an
application in the PHP language. It is a matured framework and supports modern PHP
language features. It is fun, professional, evolving and keeping pace with the current
technology.
141