Building Your First Zend Framework Application

Exclusive offer: get 50% off this eBook here
Zend Framework 2.0 by Example: Beginner’s Guide

Zend Framework 2.0 by Example: Beginner’s Guide — Save 50%

A step-by-step guide to help you build full-scale web applications using Zend Framework 2.0 with this book and ebook

$29.99    $15.00
by Krishna Shasankar V | July 2013 | Open Source PHP Web Development

In this article by Krishna Shasankar V, author of Zend Framework 2.0 by Example: Beginner’s Guide, we are going to create our first Zend Framework 2.0 project; we will be reviewing some of the key aspects of building a ZF2 MVC Application by creating modules, controllers, and views. We will be creating our own custom module in Zend Framework which will be enhanced further in subsequent chapters of this book.

(For more resources related to this topic, see here.)

Prerequisites

Before you get started with setting up your first ZF2 Project, make sure that you have the following software installed and configured in your development environment:

  • PHP Command Line Interface
  • Git : Git is needed to check out source code from various github.com repositories
  • Composer : Composer is the dependency management tool used for managing PHP dependencies

The following commands will be useful for installing the necessary tools to setup a ZF2 Project:

  • To install PHP Command Line Interface:

    $ sudo apt-get install php5-cli

  • To install Git:

    $ sudo apt-get install git

  • To install Composer:

    $ curl -s https://getcomposer.org/installer | php

ZendSkeletonApplication

ZendSkeletonApplication provides a sample skeleton application that can be used by developers as a starting point to get started with Zend Framework 2.0. The skeleton application makes use of ZF2 MVC, including a new module system.

ZendSkeletonApplication can be downloaded from GitHub (https://github.com/zendframework/ZendSkeletonApplication).

Time for action – creating a Zend Framework project

To set up a new Zend Framework project, we will need to download the latest version of ZendSkeletonApplication and set up a virtual host to point to the newly created Zend Framework project. The steps are given as follows:

  1. Navigate to a folder location where you want to set up the new Zend Framework project:

    $ cd /var/www/

  2. Clone the ZendSkeletonApplication app from GitHub:

    $ git clone git://github.com/zendframework/ ZendSkeletonApplication.git CommunicationApp

    In some Linux configurations, necessary permissions may not be available to the current user for writing to /var/www. In such cases, you can use any folder that is writable and make necessary changes to the virtual host configuration.

  3. Install dependencies using Composer:

    $ cd CommunicationApp/ $ php composer.phar self-update $ php composer.phar install

    The following screenshot shows how Composer downloads and installs the necessary dependencies:

  4. Before adding a virtual host entry we need to set up a hostname entry in our hosts file so that the system points to the local machine whenever the new hostname is used. In Linux this can be done by adding an entry to the /etc/hosts file:

    $ sudo vim /etc/hosts

    In Windows, this file can be accessed at %SystemRoot%\system32\drivers\etc\hosts.

  5. Add the following line to the hosts file:

    127.0.0.1 comm-app.local

    The final hosts file should look like the following:

  6. Our next step would be to add a virtual host entry on our web server; this can be done by creating a new virtual host's configuration file:

    $ sudo vim /usr/local/zend/etc/sites.d/vhost_comm-app-80.conf

    This new virtual host filename could be different for you depending upon the web server that you use; please check out your web server documentation for setting up new virtual hosts.

    For example, if you have Apache2 running on Linux, you will need to create the new virtual host file in /etc/apache2/sites-available and enable the site using the command a2ensite comm-app.local.

  7. Add the following configuration to the virtual host file:

    <VirtualHost *:80> ServerName comm-app.local DocumentRoot /var/www/CommunicationApp/public SetEnv APPLICATION_ENV "development" <Directory /var/www/CommunicationApp/public> DirectoryIndex index.php AllowOverride All Order allow,deny Allow from all </Directory> </VirtualHost>

    If you are using a different path for checking out the ZendSkeletonApplication project make sure that you include that path for both DocumentRoot and Directory directives.

  8. After configuring the virtual host file, the web server needs to be restarted:

    $ sudo service zend-server restart

  9. Once the installation is completed, you should be able to open http://comm-app.local on your web browser. This should take you to the following test page :

    Test rewrite rules

    In some cases, mod_rewrite may not have been enabled in your web server by default; to check if the URL redirects are working properly, try to navigate to an invalid URL such as http://comm-app.local/12345; if you get an Apache 404 page, then the .htaccess rewrite rules are not working; they will need to be fixed, otherwise if you get a page like the following one, you can be sure of the URL working as expected.

What just happened?

We have successfully created a new ZF2 project by checking out ZendSkeletonApplication from GitHub and have used Composer to download the necessary dependencies including Zend Framework 2.0. We have also created a virtual host configuration that points to the project's public folder and tested the project in a web browser.

Alternate installation options

We have seen just one of the methods of installing ZendSkeletonApplication; there are other ways of doing this.

You can use Composer to directly download the skeleton application and create the project using the following command:

$ php composer.phar create-project --repositoryurl="
http://packages.zendframework.com" zendframework/
skeleton-application path/to/install

You can also use a recursive Git clone to create the same project:

$ git clone git://github.com/zendframework/
ZendSkeletonApplication.git --recursive

Refer to:

http://framework.zend.com/downloads/skeleton-app

Zend Framework 2.0 – modules

In Zend Framework, a module can be defined as a unit of software that is portable and reusable and can be interconnected to other modules to construct a larger, complex application.

Modules are not new in Zend Framework, but with ZF2, there is a complete overhaul in the way modules are used in Zend Framework. With ZF2, modules can be shared across various systems, and they can be repackaged and distributed with relative ease. One of the other major changes coming into ZF2 is that even the main application is now converted into a module; that is, the application module.

Some of the key advantages of Zend Framework 2.0 modules are listed as follows:

  • Self-contained, portable, reusable
  • Dependency management
  • Lightweight and fast
  • Support for Phar packaging and Pyrus distribution

Zend Framework 2.0 – project folder structure

The folder layout of a ZF2 project is shown as follows:

Zend Framework 2.0 – project folder structure

Folder name

Description

config

Used for managing application configuration.

data

Used as a temporary storage location for storing application

data including cache files, session files, logs, and indexes.

module

Used to manage all application code.

module/Application

This is the default application module that is provided with

ZendSkeletonApplication.

public

This is the default application module that is provided with

ZendSkeletonApplication.

vendor

Used to manage common libraries that are used by the

application. Zend Framework is also installed in this folder.

vendor/zendframework

endor/zendframework Zend Framework 2.0 is installed here.

Time for action – creating a module

Our next activity will be about creating a new Users module in Zend Framework 2.0. The Users module will be used for managing users including user registration, authentication, and so on. We will be making use of ZendSkeletonModule provided by Zend, shown as follows:

  1. Navigate to the application's module folder:

    $ cd /var/www/CommunicationApp/ $ cd module/

  2. Clone ZendSkeletonModule into a desired module name, in this case it is Users:

    $ git clone git://github.com/zendframework/ZendSkeletonModule.git Users

  3. After the checkout is complete, the folder structure should look like the following screenshot:

    Time for action – creating a module

  4. Edit Module.php ; this file will be located in the Users folder under modules (CommunicationApp/module/Users/module.php) and change the namespace to Users. Replace namespace ZendSkeletonModule; with namespace Users;.
  5. The following folders can be removed because we will not be using them in our project:

    * Users/src/ZendSkeletonModule

    * Users/view/zend-skeleton-module

What just happened?

We have installed a skeleton module for Zend Framework; this is just an empty module, and we will need to extend this by creating custom controllers and views. In our next activity, we will focus on creating new controllers and views for this module.

Creating a module using ZFTool

ZFTool is a utility for managing Zend Framework applications/projects, and it can also be used for creating new modules; in order to do that, you will need to install ZFTool and use the create module command to create the module using ZFTool:

$ php composer.phar require zendframework/zftool:dev-master $ cd vendor/zendframework/zftool/ $ php zf.php create module Users2 /var/www/CommunicationApp

Read more about ZFTool at the following link:
http://framework.zend.com/manual/2.0/en/modules/zendtool.introduction.html

MVC layer

The fundamental goal of any MVC Framework is to enable easier segregation of three layers of the MVC, namely, model, view, and controller. Before we get to the details of creating modules, let's quickly try to understand how these three layers work in an MVC Framework:

  • Model : The model is a representation of data; the model also holds the business logic for various application transactions.
  • View : The view contains the display logic that is used to display the various user interface elements in the web browser.
  • Controller : The controller controls the application logic in any MVC application; all actions and events are handled at the controller layer. The controller layer serves as a communication interface between the model and the view by controlling the model state and also by representing the changes to the view. The controller also provides an entry point for accessing the application.
  • In the new ZF2 MVC structure, all the models, views, and controllers are grouped by modules. Each module will have its own set of models, views, and controllers, and will share some components with other modules.

Zend Framework module – folder structure

The folder structure of Zend Framework 2.0 module has three vital components—the configurations, the module logic, and the views. The following table describes how contents in a module are organized:

Folder name

Description

config

Used for managing module configuration

src

Contains all module source code, including all controllers and models

view

Used to store all the views used in the module

Time for action – creating controllers and views

Now that we have created the module, our next step would be having our own controllers and views defined. In this section, we will create two simple views and will write a controller to switch between them:

  1. Navigate to the module location:

    $ cd /var/www/CommunicationApp/module/Users

  2. Create the folder for controllers:

    $ mkdir -p src/Users/Controller/

  3. Create a new IndexController file, < ModuleName >/src/<ModuleName>/Controller/:

    $ cd src/Users/Controller/ $ vim IndexController.php

  4. Add the following code to the IndexController file:

    <?php namespace Users\Controller; use Zend\Mvc\Controller\AbstractActionController; use Zend\View\Model\ViewModel; class IndexController extends AbstractActionController { public function indexAction() { $view = new ViewModel(); return $view; } public function registerAction() { $view = new ViewModel(); $view->setTemplate('users/index/new-user'); return $view; } public function loginAction() { $view = new ViewModel(); $view->setTemplate('users/index/login'); return $view; } }

  5. The preceding code will do the following actions; if the user visits the home page, the user is shown the default view; if the user arrives with an action register, the user is shown the new-user template; and if the user arrives with an action set to login, then the login template is rendered.
  6. Now that we have created the controller, we will have to create necessary views to render for each of the controller actions.
  7. Create the folder for views:

    $ cd /var/www/CommunicationApp/module/Users $ mkdir -p view/users/index/

  8. Navigate to the views folder, <Module>/view/<module-name>/index:

    $ cd view/users/index/

  9. Create the following view files:
    • index
    • login
    • new-user
    1. For creating the view/users/index/index.phtml file, use the following code:

      <h1>Welcome to Users Module</h1> <a href="/users/index/login">Login</a> | <a
      href = "/users/index/register">New User Registration</a>

    2. For creating the view/users/index/login.phtml file, use the following code:

      <h2> Login </h2> <p> This page will hold the content for the login form </p> <a href="/users"><< Back to Home</a>

    3. For creating the view/users/index/new-user.phtml file, use the following code:

      <h2> New User Registration </h2> <p> This page will hold the content for the registration form </p> <a href="/users"><< Back to Home</a>

What just happened?

We have now created a new controller and views for our new Zend Framework module; the module is still not in a shape to be tested. To make the module fully functional we will need to make changes to the module's configuration, and also enable the module in the application's configuration.

Zend Framework module – configuration

Zend Framework 2.0 module configuration is spread across a series of files which can be found in the skeleton module. Some of the configuration files are described as follows:

  • Module.php: The Zend Framework 2 module manager looks for the Module.php file in the module's root folder. The module manager uses the Module.php file to configure the module and invokes the getAutoloaderConfig() and getConfig() methods.
  • autoload_classmap.php: The getAutoloaderConfig() method in the skeleton module loads autoload_classmap.php to include any custom overrides other than the classes loaded using the standard autoloader format. Entries can be added or removed to the autoload_classmap.php file to manage these custom overrides.
  • config/module.config.php: The getConfig() method loads config/module.config.php; this file is used for configuring various module configuration options including routes, controllers, layouts, and various other configurations.

Time for action – modifying module configuration

In this section will make configuration changes to the Users module to enable it to work with the newly created controller and views using the following steps:

  1. Autoloader configuration – The default autoloader configuration provided by the ZendSkeletonModule needs to be disabled; this can be done by editing autoload_classmap.php and replacing it with the following content:

    <?php return array();

  2. Module configuration – The module configuration file can be found in config/module.config.php; this file needs to be updated to reflect the new controllers and views that have been created, as follows:
    • Controllers – The default controller mapping points to the ZendSkeletonModule; this needs to be replaced with the mapping shown in the following snippet:

      'controllers' => array( 'invokables' => array( 'Users\Controller\Index' =>
      'Users\Controller\IndexController',
      ), ),

    • Views – The views for the module have to be mapped to the appropriate view location. Make sure that the view uses lowercase names separated by a hyphen (for example, ZendSkeleton will be referred to as zend-skeleton):

      'view_manager' => array( 'template_path_stack' => array( 'users' => __DIR__ . '/../view', ), ),

    • Routes – The last module configuration is to define a route for accessing this module from the browser; in this case we are defining the route as /users, which will point to the index action in the Index controller of the Users module:

      'router' => array( 'routes' => array( 'users' => array( 'type' => 'Literal', 'options' => array( 'route' => '/users', 'defaults' => array( '__NAMESPACE__' => 'Users\Controller', 'controller' => 'Index', 'action' => 'index', ), ),

  3. After making all the configuration changes as detailed in the previous sections, the final configuration file, config/module.config.php, should look like the following:

    <?php return array( 'controllers' => array( 'invokables' => array( 'Users\Controller\Index' => 'Users\Controller\IndexController', ), ), 'router' => array( 'routes' => array( 'users' => array( 'type' => 'Literal', 'options' => array( // Change this to something specific to your module 'route' => '/users', 'defaults' => array( //Change this value to reflect the namespace in which // the controllers for your module are found '__NAMESPACE__' => 'Users\Controller', 'controller' => 'Index', 'action' => 'index', ), ), 'may_terminate' => true, 'child_routes' => array( // This route is a sane default when developing a module; // as you solidify the routes for your module, however, // you may want to remove it and replace it with more // specific routes. 'default' => array( 'type' => 'Segment', 'options' => array( 'route' => '/[:controller[/:action]]', 'constraints' => array( 'controller' => '[a-zA-Z][a-zA-Z0-9_-]*', 'action' => '[a-zA-Z][a-zA-Z0-9_-]*', ), 'defaults' => array( ), ), ), ), ), ), ), 'view_manager' => array( 'template_path_stack' => array( 'users' => __DIR__ . '/../view', ), ), );

  4. Application configuration – Enable the module in the application's configuration—this can be done by modifying the application's config/application.config.php file, and adding Users to the list of enabled modules:

    'modules' => array( 'Application', 'Users', ),

  5. To test the module in a web browser, open http://comm-app.local/users/ in your web browser; you should be able to navigate within the module.

The module home page is shown as follows:

The registration page is shown as follows:

What just happened?

We have modified the configuration of ZendSkeletonModule to work with the new controller and views created for the Users module. Now we have a fully-functional module up and running using the new ZF module system.

Have a go hero

Now that we have the knowledge to create and configure own modules, your next task would be to set up a new CurrentTime module. The requirement for this module is to render the current time and date in the following format:

Time: 14:00:00 GMT Date: 12-Oct-2012

Summary

We have now learned about setting up a new Zend Framework project using Zend's skeleton application and module. In our next chapters, we will be focusing on further development on this module and extending it into a fully-fledged application.

Resources for Article :


Further resources on this subject:


Zend Framework 2.0 by Example: Beginner’s Guide A step-by-step guide to help you build full-scale web applications using Zend Framework 2.0 with this book and ebook
Published: July 2013
eBook Price: $29.99
Book Price: $49.99
See more
Select your format and quantity:

About the Author :


Krishna Shasankar V

Krishna Shasankar V is a web developer with 7 years of extensive development experience in PHP. He leads a team of engineers at Lister Technologies developing enterprise class retail and e-commerce solutions.

He is a Zend Certified Engineer in PHP 5 and Zend Framework. He also has a Bachelor's degree in Information Technology from Anna University, Chennai, and a Master's degree in Software Systems from Birla Institute of Technology and Science, Pilani.

In his spare time, he enjoys music, photography, and travel (especially when combined). You can contact Krishna and leave some comments on his blog (www.clickoffline.com).

Books From Packt


Zend Framework 1.8 Web Application Development
Zend Framework 1.8 Web Application Development

 CouchDB and PHP Web Development Beginner's Guide
CouchDB and PHP Web Development Beginner's Guide

 Ext JS 4 Web Application Development Cookbook
Ext JS 4 Web Application Development Cookbook

 Socket.IO Real-time Web Application Development
Socket.IO Real-time Web Application Development

Magento 1.4 Development Cookbook
Magento 1.4 Development Cookbook

 RESTful PHP Web Services
RESTful PHP Web Services

 PHP Application Development with NetBeans: Beginner's Guide
PHP Application Development with NetBeans: Beginner's Guide

 Expert PHP 5 Tools
Expert PHP 5 Tools


No votes yet

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
L
S
h
e
c
U
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software