Order Now

Zend

Table of contents :

What is the Zend Framework?

The Zend Framework is a software framework written in PHP. It is intended as a practical and reasonable solution for common web application purposes. As a powerful high-quality open-source framework, its main focus targets the development of modern web applications and popular web services. It has ready-made components for Amazon, Last.fm, Del.icio.us, Flickr, Google and more. The Zend Framework has adopted a Model-View-Controller (MVC) architecture. This enables developers to differentiate the separate constituents of an application in order to make its development and maintenance much easier and simpler to handle. Zend also supplies developers with a set of classes for building web applications or connecting different web services.

Latest version: 1.7.0
PHP4
PHP5 PHP v.5.2.4 or later
MVC
Multiple DB
ORM
DB Objects
Templates
Caching
Validation
Ajax
Auth Module
Modules
Cost FREE


Overview of the Zend Framework

The first thing that we have to mention about the Zend Framework is that it is software entirely written in PHP v.5. PHP v.5 represents a major advancement over the previous models of Object Oriented programming in PHP. And that may well be one of the main reasons why you should choose the Zend Framework. Zend version 1.7.0 and all later Zend versions require PHP v.5.2.4, or later, to be supported on the server.

The framework is built on the bases of modular components. These may be used as standalone solutions or coupled with other components. That makes the Zend framework structure very flexible indeed. Many interfaces have been created to make the different components as extensible and portable, as well as loosely dependent on each other, as possible.

How Zend Framework's MVC architecture works

As an example of the way the Zend Framework works with the MVC model, we will create a simple form that submits data to a MySQL database and lists the already submitted values.

The first step is to create an MVC directory structure:

Example of MVC directory structure

*application
---config
---controllers
---models
---views
---layouts
*public
*library

The "public" directory is the one that will be opened by the domain we are using.
The "library" directory contains the Zend Framework components so that we can easily load them.
The "application" and all its sub-directories represent the directory model-controller-view structure.
Now we need to create a database and describe it in application/config/config.ini as follows:

How to discribe a database in the config.ini file

[general]
db.adapter = PDO_MYSQL
// The MySQL Host
db.params.host = localhost
//The database username
db.params.username = username
//The database password
db.params.password = password
//The database name
db.params.dbname = database

The table we will be using can be created with the following SQL statement:

Example of how to create MySQL table

CREATE TABLE `forms` (
`id` int(11) NOT NULL auto_increment,
`title` varchar(100) NOT NULL,
`data` varchar(100) NOT NULL,
PRIMARY KEY  (`id`)
);

All incoming requests will be handled by the following index.php file in the public/ directory:

Example for a index.php file

<?php

// Define the include path so that we can use the Zend Framework libraries
set_include_path('../library/:../application/models:' . get_include_path());

//Allow the Zend Framework to automatically load classes
include "Zend/Loader.php";
Zend_Loader::registerAutoload();

//Get the database configuration, using the Zend_Config component
$config = new Zend_Config_Ini('../application/config/config.ini', 'general');

//The Zend_Registry component aids us in storing the config data in the application space.
$reg = Zend_Registry::getInstance();
$reg->set('config', $config);

//Configure the database
$db = Zend_Db::factory($config->db);
Zend_Db_Table::setDefaultAdapter($db);

//Configure the controller and the layout
$frontController = Zend_Controller_Front::getInstance();
$frontController->setControllerDirectory('../application/controllers');
Zend_Layout::startMvc(array('layoutPath'=>'../application/layouts'));

//Start it!
$frontController->dispatch();

Note that there is no PHP closing tag ("?>"). The dispatch() takes over from there.
Now we will define the controller which will be handling our form. ./application/controllers/IndexController.php

<?php

class IndexController extends Zend_Controller_Action
{
//define the action that will be performed when index is requested
function indexAction()
{
//Assign the variable $title to be with value "My Form" in the view.
$this->view->title = "My Form";
//Make an instance of the FormsTable model that will handle the database queries
$forms = new FormsTable();
//Get all the data from the database and assign it to the variable $forms
$this->view->forms = $forms->fetchAll();

 

        //Make an instance of the Form model it will assign all the attributes to the form
$form = new Form();
//Assign $form variable with value $form, which will be used in the view
$this->view->form = $form;

        //Handle the post of new values
if ($this->_request->isPost()) {
//If the data is successfully assigned and validated
$formData = $this->_request->getPost();
if ($form->isValid($formData)) {
//Assign the data to a new row and save it
$row = $forms->createRow();
$row->data = $form->getValue('data');
$row->title = $form->getValue('title');
$row->save();

                //Redirect back to the index page  
$this->_redirect('/');
}
}
}
}

The two models are as follows:

Example for a /application/models/Form.php file

<?php

class Form extends Zend_Form
{
public function __construct($options = null)
{
//Load the constructor of the Form object, so that we can actually have a form
parent::__construct($options);
//This one will define the id of the form html tag
$this->setName('form');

       //Define the data field of the form and set some example options
$data = new Zend_Form_Element_Text('data');
$data->setLabel('Data')
->setRequired(true)
->addFilter('StripTags')
->addFilter('StringTrim')
->addValidator('NotEmpty');

       //Define the title field of the form and set some example options
$title = new Zend_Form_Element_Text('title');
$title->setLabel('Title')
->setRequired(true)
->addFilter('StripTags')
->addFilter('StringTrim')
->addValidator('NotEmpty');

        //Define the submit button
$submit = new Zend_Form_Element_Submit('submit');
$submit->setAttrib('id', 'submitbutton');
$submit->setLabel('Add');
//Add the elements to the form
$this->addElements(array($id, $title, $data, $submit));
}
}

Example for a /application/models/FormsTable.php file

<?php

//Create an interface to the table forms
class FormsTable extends Zend_Db_Table
{
//define the table that we will make queries to
protected $_name = 'forms';
}

The last step is to create the layout and the view of the page:

Example for a /application/layouts/layout.phtml file

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<!-- The title that we have defined in the controller -->
<title><?php echo $this->escape($this->title); ?></title>
</head>
<body>
<div id="content">
<h1><?php echo $this->escape($this->title); ?></h1>
<!-— Get the page content --> 
<?php echo $this->layout()->content; ?>
</div>
</body>

</html>
The view will only cycle through the defined variables to display the data that we need for our index page.

Example for a /application/views/scripts/index/index.phtml

<table border="1">
<tr>
<th>Title</th>
<th>Data</th>
</tr>
<?php foreach($this->forms as $form) { ?>
<tr>
<td><?php echo $this->escape($form->title);?></td>
<td><?php echo $this->escape($form->data);?></td>
</tr>
<?php } ?>
</table>
<?php echo $this->form ;?>

Now we have a fully operational form using MySQL database.

Zend Famework's commonly used components

Below is a list of some of the most common Zend framework components with a short description.

For more information and detailed description of the components and their usage, you can view the complete list available on the Zend framework’s website:
http://framework.zend.com/manual/en/

Zend_Db - Zend_Db guarantees easy and simple work with databases. This database abstraction layer ranks higher and expands the functionality of the native PHP Data Objects (PDO) database extension. PDO basically enables developers to quickly create a typical database functionality core by using any of the PDO drivers - PDO_Mysql, PDO_PgSQL, PDO_Sqlite, etc. Using this speed advantage of PDO and inputting its resources to do the bigger part of the work, PDO wrapper libraries like Zend_Db supplement the functionality of PDO with their own wrapper code thus providing you with a considerably light, yet feature-rich database abstraction layer.

Example for PDO_MySQL connect

try {
    $mysql_db = new PDO('mysql:host=ntchosting.com;dbname=phonebook', 'user', 'password');

} catch (PDOException $e){
    die($e->getMessage);

}

What stands out compared to the functionality of the PDO extension is that, Zend_Db allows the creation of a database connection adapter without binding you to a specific database engine.

Example for MySQL connection using Zend_Db

<?php

require_once 'Zend.php';

Zend::loadClass("Zend_Db");

$params = array ('host'     => 'ntchosting.com',
                 'username' => 'user',
                 'password' => 'password',
                 'dbname'   => 'phonebook');

$db = Zend_Db::factory('PDO_MYSQL', $params);

?>

Zend_Auth - Zend_Auth is a modular component that provides an API (application programming interface) for authentication and comprises specific authentication adapters for typical and common met scenarios. With a Zend_Auth adapter developers can program authentication protocol that can be run with a particular type of authentication service, such as Lightweight Directory Access Protocol - LDAP, Relational database management systems - RDBMS, or file-based storage. Basic features that the authentication protocol of a Zend_Auth adapter includes are: accepting authentication credentials, running queries with the authentication service, and returning results.

Each Zend_Auth adapter class runs via a Zend_Auth_Adapter_Interface and must be made ready in advance before calling authenticate(). Typical preparation of the adapter may include configuring credentials (e.g., username and password) and setting up values for adapter-specific configuration options (for example, database connection settings for a database table adapter).

Example for authentication adapter Zend_Auth

{
    public function __construct($username, $password)
    {
        // ...
    }
    public function authenticate()
    {
        // ...
    }
}

Zend_Acl - The Zend_Acl modular component has specific function - it allows the implementation of a lightweight and provides a flexible Access Control List (ACL) system which can restrict the access to certain resources taking into consideration the role assigned to each user. More particularly, a given application may use such ACL's to ensure access control of certain protected objects that are being requested by different other objects. In Zend_Acl a role can take over the characteristics from another role or more other roles. This practically means that inheritance of rules is supported amongst roles. In order to "keep it simple" developers can "sort things out" by simply implementing a class determining the relationship between roles and resources.

For example, a user role, such as "johndoe", may fall into the group of one or more parent roles, such as "guest" and "admin". The developer needs to assign separate rules to "guest" and "admin", and the user role "johndoe" will inherit those rules from both parent roles. The developer won't need to specifically assign rules to "johndoe".

Example for Zend_Acl component

<?php
class NTCExample_Acl extends Zend_Acl
{
public function __construct(Zend_Auth $auth)
{
// Add Resources
// Resource 1: Frontend Module
$this->add(new Zend_Acl_Resource(‘frontend’));
// Resource #2: Administration Module
$this->add(new Zend_Acl_Resource(‘administration’));
        // Add Roles
        // Role 1: Guest
$this->addRole(new Zend_Acl_Role(‘guest’));
// Role 2: Administrator (inherits from Guest)
$this->addRole(new Zend_Acl_Role(‘admin’));
       //Role 3 A user role Johndoe which belongs to an admin parent role
$parents = array('guest','admin');
       $this->addRole(new Zend_Acl_Role('johndoe'), $parents );
        // Assign Access Rules
        // Rule 1 & 2: Guests can access Frontend Module and Johndoe inherits this
$this->allow(‘guest’, ‘default’);
// Rule 3 & 4: Johndoe can access Administration Module and the Guests are denied by default
$this->allow(‘admin’, ‘administration’);

Zend_Session - One PHP session is in fact a very logical and consistent one-to-one communication between server-side persistent state data and a given user agent client (for example, a web browser). The Zend_Session modular component helps managing and storing session data. Session data is a coherent supplement of cookie data. However, its range spans over multiple pages requested by the user agent client. Also, unlike cookie data, the session data is not saved at the client side and is made available to the client only if the server-side source code voluntarily discloses that data in response to an explicit client request.

Example for Zend_Session component

//$myNamespace corresponds to $_SESSION['myNamespace']
$myNamespace = new Zend_Session_Namespace('myNamespace');

Zend_Http_Cookie - Zend_Http_Cookie is a class that is in nature an HTTP cookie. It provides means for parsing HTTP response strings, gathering cookies, and a simple way of viewing their properties. Checks for secure connection can be performed through this modular component as well.

Example for a simple cookie using Zend_Http_Cookie

//This cookie will expire in 2 hours
$cookie = new Zend_Http_Cookie('foo',
'bar',
'.ntchosting.com',
time() + 7200,
'/path');

Example for a cookie which can be sent over a secure connection

$cookie = Zend_Http_Cookie::fromString('foo=bar; domain=.ntchosting.com; ' .
'path=/path; secure');

Example for a cookie when the cookie's domain is not set

$cookie = Zend_Http_Cookie::fromString('foo=bar; secure;',
'http://www.example.com/path');

Some modular components integrate very essential software design patterns, such as the Model-View-Controller architecture, the Factory pattern and the Singleton pattern.

Resources:




1 2 3 4