Google News
logo
Zend framework Interview Questions
Zend Framework is an open source, object oriented web application framework for PHP 5. Zend Framework is often called a 'component library', because it has many loosely coupled components that you can use more or less independently. But Zend Framework also provides an advanced Model-View-Controller (MVC) implementation that can be used to establish a basic structure for your Zend Framework applications.

A full list of Zend Framework components along with short descriptions may be found in the » components overview. This QuickStart will introduce you to some of Zend Framework's most commonly used components, including Zend_Controller, Zend_Layout, Zend_Config, Zend_Db, Zend_Db_Table, Zend_Registry, along with a few view helpers.
Zend Technologies develop a Zend Framework. It is a Cupertino, California, U.S.-based World Wide Web infrastructure Software Company founded by Andi Gutmans and Zeev Suraski in 1999. The Zend framework was initially released on March 3, 2006.
Zend Framework requires PHP 5.2.4 and above versions. Zend framework is enhanced to utilize all of the object-oriented features of PHP 5.2.4 and have the advantage of prominent security and performance enhancements.
Here are the following steps to install Zend in a local machine:
 
Step 1: Create a new SSH user.
 
Step 2: Create a fully hosted domain or subdomain.
 
Step 3: Create a phprc file.
 
Step 4: Change the default PHP CLI the user shell uses.
 
Step 5: Download the Zend framework.
 
Step 6: Log in to the server via SSH.
 
Step 7: Change the directory of the project.
 
Step 8: Close the repository and change the directory.
 
Step 9: Then, locally install the composer into the directory.
 
Step 10: Run the following syntax to install the Zend framework.
[server]$ php composer.phar self-update  
[server]$ php composer.phar install  
Below are some features of the Zend framework, such as:
 
* Zend provides RESTful API development support.
* It has flexible URI Routing and session management.
* Zend has a simple cloud API.
* It supports multi databases, including PostgreSQL, SQLite, etc.
* It is a pure object-oriented web application framework.
* It supports advanced MVC implementation.
* Code is reusable and easier to maintain.
* It provides data encryption.
 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.
We will build a very simple inventory system to display our album collection. The home page will list our collection and allow us to add, edit and delete albums. Hence the following pages are required :
Page Description
Home This will display the list of albums and provide links to edit and delete them. Also, a link to enable adding new albums will be provided.
Add new album This page will provide a form for adding a new album.
Edit album This page will provide a form for editing an album.
Delete album This page will confirm that we want to delete an album and then delete it.

Before we set up our files, it's important to understand how the framework expects the pages to be organised. Each page of the application is known as an action and actions are grouped into controllers within modules. Hence, you would generally group related actions into a controller; for instance, a news controller might have actions of current, archived, and view.
 
As we have four pages that all apply to albums, we will group them in a single controller AlbumController within our Album module as four actions. The four actions will be :

Page Controller Action
Home AlbumController index
Add new album AlbumController add
Edit album AlbumController edit
Delete album AlbumController delete

The mapping of a URL to a particular action is done using routes that are defined in the module’s module.config.php file. We will add a route for our album actions. This is the updated module config file with the new code highlighted using comments.
namespace Album;

use Zend\Router\Http\Segment;
use Zend\ServiceManager\Factory\InvokableFactory;

return [
    'controllers' => [
        'factories' => [
            Controller\AlbumController::class => InvokableFactory::class,
        ],
    ],

    // The following section is new and should be added to your file:
    'router' => [
        'routes' => [
            'album' => [
                'type'    => Segment::class,
                'options' => [
                    'route' => '/album[/:action[/:id]]',
                    'constraints' => [
                        'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
                        'id'     => '[0-9]+',
                    ],
                    'defaults' => [
                        'controller' => Controller\AlbumController::class,
                        'action'     => 'index',
                    ],
                ],
            ],
        ],
    ],

    'view_manager' => [
        'template_path_stack' => [
            'album' => __DIR__ . '/../view',
        ],
    ],
];
The name of the route is ‘album’ and has a type of ‘segment’. The segment route allows us to specify placeholders in the URL pattern (route) that will be mapped to named parameters in the matched route. In this case, the route is /album[/:action[/:id]] which will match any URL that starts with /album. The next segment will be an optional action name, and then finally the next segment will be mapped to an optional id. The square brackets indicate that a segment is optional. The constraints section allows us to ensure that the characters within a segment are as expected, so we have limited actions to starting with a letter and then subsequent characters only being alphanumeric, underscore, or hyphen. We also limit the id to digits.
 
This route allows us to have the following URLs :

URL Page Action
/album Home (list of albums) index
/album/add Add new album add
/album/edit/2 Edit album with an id of 2 edit
/album/delete/4 Delete album with an id of 4 delete
We are now ready to set up our controller. For zend-mvc, the controller is a class that is generally called {Controller name}Controller; note that {Controller name} must start with a capital letter. This class lives in a file called {Controller name}Controller.php within the Controller subdirectory for the module; in our case that is module/Album/src/Controller/. Each action is a public method within the controller class that is named {action name}Action, where {action name} should start with a lower case letter.
 
Conventions not strictly enforced : This is by convention. zend-mvc doesn't provide many restrictions on controllers other than that they must implement the Zend\Stdlib\Dispatchable interface. The framework provides two abstract classes that do this for us: Zend\Mvc\Controller\AbstractActionController and Zend\Mvc\Controller\AbstractRestfulController. We'll be using the standard AbstractActionController, but if you’re intending to write a RESTful web service, AbstractRestfulController may be useful.
 
Let’s go ahead and create our controller class in the file zf-tutorials/module/Album/src/Controller/AlbumController.php :
namespace Album\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

class AlbumController extends AbstractActionController
{
    public function indexAction()
    {
    }

    public function addAction()
    {
    }

    public function editAction()
    {
    }

    public function deleteAction()
    {
    }
}
We have now set up the four actions that we want to use. They won't work yet until we set up the views. The URLs for each action are :

URL Method called
http://zf-tutorial.localhost/album Album\Controller\AlbumController::indexAction
http://zf-tutorial.localhost/album/add Album\Controller\AlbumController::addAction
http://zf-tutorial.localhost/album/edit Album\Controller\AlbumController::editAction
http://zf-tutorial.localhost/album/delete Album\Controller\AlbumController::deleteAction

We now have a working router and the actions are set up for each page of our application.
 
It's time to build the view and the model layer.
The Zend_Controller_Front implements the front controller pattern used in the Model-View-Controller of applications in the Zend framework. Its main purpose is to manage the request, route the incoming request, and then dispatch actions.
In the Zend framework, then bootstrapping is the process to load the application. All the resources required to apply the request to the application are bootstrapped/loaded/initialized before the request is completed.
Zend framework provides three types of components, such as :
 
Event Manager : It provides the ability to create event-based programming. It also helps to create, inject and manage new events.

Service Manager : It provides the ability to consume any services from anywhere with little effort.

Module manager : It provides the ability to convert a collection of PHP classes with identical functionality into a single unit. It can use to be maintained and configured as a single unit.
In Zend Framework, Zend_Form is used to create an HTML form. It provides various components, such as input, select, radio, checkbox, etc. below are the following features of the Zend form.
 
* Filtering and validation
* Ordering
* Element and Form rendering, including escaping
* Element and form grouping
* Element and form-level configuration
We can check whether a form is posted or not in Zend Framework in the following two ways :
 
* Process the form submission and store it in the database.
* Display a form for the user to provide details.

We utilize Zend\form to check whether a form is posted or not in a Zend framework. The Zend\Form component manages the form and form validation.
Following are the front controller in the Zend Framework :
 
routeStartup : This function is called before Zend_Controller_Front calls on the router to evaluate the request.

routeShutdown : This function is called after the router finishes routing the request.

preDispatch : It is called before the dispatcher dispatches an action.

dispatchLoopStartup : It is used before enters of Zend_Controller_Front.

postDispatch : It is called after the dispatcher dispatches an action.
Here are the following benefits of the Zend framework over the other frameworks of PHP.
 
* Zend is a fully object-oriented framework and utilizes many object-oriented concepts such as interfaces and inheritance.
* It builds web applications more comfortably and faster.
* It supports multiple vendors and database systems.
* Zend has excellent scope for customization.
* It supports an attractive and meaningful URL database.
* Zend framework composes and sends email features.
Dependency Injection is a concept that has been talked about in numerous places over the web. For the purposes of this quickstart, we’ll explain the act of injecting dependencies simply with this below code :

$b = new B(new A());
Above, A is a dependency of B, and A was injected into B. If you are not familiar with the concept of dependency injection, here are a couple of great reads: Matthew Weier O’Phinney’s Analogy, Ralph Schindler’s Learning DI, or Fabien Potencier’s Series on DI.
 
Simplest usage case (2 classes, one consumes the other) : In the simplest use case, a developer might have one class (A) that is consumed by another class (B) through the constructor. By having the dependency injected through the constructor, this requires an object of type A be instantiated before an object of type B so that A can be injected into B.
namespace My {

    class A
    {
        /* Some useful functionality */
    }

    class B
    {
        protected $a = null;
        public function __construct(A $a)
        {
            $this->a = $a;
        }
    }
}
To create B by hand, a developer would follow this work flow, or a similar workflow to this:

$b = new B(new A());

If this workflow becomes repeated throughout your application multiple times, this creates an opportunity where one might want to DRY up the code. While there are several ways to do this, using a dependency injection container is one of these solutions. With Zend’s dependency injection container Zend\Di\Di, the above use case can be taken care of with no configuration (provided all of your autoloading is already configured properly) with the following usage:
$di = new Zend\Di\Di;
$b = $di->get('My\B'); // will produce a B object that is consuming an A object
Moreover, by using the Di::get() method, you are ensuring that the same exact object is returned on subsequent calls. To force new objects to be created on each and every request, one would use the Di::newInstance() method:

$b = $di->newInstance('My\B');

Let’s assume for a moment that A requires some configuration before it can be created. Our previous use case is expanded to this (we’ll throw a 3rd class in for good measure):
namespace My {

    class A
    {
        protected $username = null;
        protected $password = null;
        public function __construct($username, $password)
        {
            $this->username = $username;
            $this->password = $password;
        }
    }

    class B
    {
        protected $a = null;
        public function __construct(A $a)
        {
            $this->a = $a;
        }
    }

    class C
    {
        protected $b = null;
        public function __construct(B $b)
        {
            $this->b = $b;
        }
    }

}
With the above, we need to ensure that our Di is capable of setting the A class with a few configuration values (which are generally scalar in nature). To do this, we need to interact with the InstanceManager:
$di = new Zend\Di\Di;
$di->getInstanceManager()->setProperty('A', 'username', 'MyUsernameValue');
$di->getInstanceManager()->setProperty('A', 'password', 'MyHardToGuessPassword%$#');
Now that our container has values it can use when creating A, and our new goal is to have a C object that consumes B and in turn consumes A, the usage scenario is still the same:
$c = $di->get('My\C');
// or
$c = $di->newInstance('My\C');
Simple enough, but what if we wanted to pass in these parameters at call time? Assuming a default Di object ($di = new Zend\Di\Di() without any configuration to the InstanceManager), we could do the following:
$parameters = array(
    'username' => 'MyUsernameValue',
    'password' => 'MyHardToGuessPassword%$#',
);

$c = $di->get('My\C', $parameters);
// or
$c = $di->newInstance('My\C', $parameters);
Constructor injection is not the only supported type of injection. The other most popular method of injection is also supported: setter injection. Setter injection allows one to have a usage scenario that is the same as our previous example with the exception, for example, of our B class now looking like this:
namespace My {
    class B
    {
        protected $a;
        public function setA(A $a)
        {
            $this->a = $a;
        }
    }
}
Since the method is prefixed with set, and is followed by a capital letter, the Di knows that this method is used for setter injection, and again, the use case $c = $di->get('C'), will once again know how to fill the dependencies when needed to create an object of type C.
 
Other methods are being created to determine what the wirings between classes are, such as interface injection and annotation based injection.
The Zend\Authentication component provides an API for authentication and includes concrete authentication adapters for common use case scenarios.
 
Zend\Authentication is concerned only with authentication and not with authorization. Authentication is loosely defined as determining whether an entity actually is what it purports to be (i.e., identification), based on some set of credentials. Authorization, the process of deciding whether to allow an entity access to, or to perform operations upon, other entities is outside the scope of Zend\Authentication.
In the Zend Framework, the application.ini file is used for the configuration of the application. This file is located in the application/configs/application.ini location.
Here are some common differences between Zend_Auth and Zend_Acl, such as :

Zend_Auth Zend_Acl
Zend_Auth utilizes the method like OpenID, LDAP, and HTTP to provide the confirmation. Zend_Acl utilizes Access Control List for approval.
Zend_Auth gives the validation protocol to the clients utilizing numerous methods. Zend_Acl is utilized for approval purposes.
Zend_Auth confirms checking and providing the certifications to the client's system. Zend_Acl utilizes the list of parts that are being implemented, just the approved individuals.
Zend_Auth supports the authentication stages features. Zend_Acl supports the propelled definitions with features of different legacy and other similar highlights.
Zend_Auth gives an environment to the framework through which the user is authenticated for utilize. Zend_Acl plays out a few tasks on the particular assets that need to be composed on the system.
Zend framework utilizes the decorator pattern to render elements and forms. The decorator is generally used to comply with the single responsibility principle as it admits functionality to be divided between classes with unique areas of concern.
 
One basic technique to define a common decorator pattern is a design that allows the behavior to be added to a particular object, either statically or dynamically, without affecting various other objects from the same class.
Decorators are utilized as a part of the application to give the functionality and make components work. The default methods, which are provided by decorators in the Zend framework, are as follows :
 
View Helper : It is a strategy that permits the review of the helper files utilized. It permits the replacement of the substance that is being given.

Errors : It gives the error codes and messages that came during the execution of the application. It gives attaching of the substance.

HTML Tag : It enables the labels to be written by utilizing the parameters and attributes. It gives the wrapping up of the substance and decreasing the length of the code.

Labels : Labels are utilized to give the informative keywords as it gives pre-pending of the substance that is being given.
Lucene is a superior, full-featured text search engine that uses an open, binary format for putting search indexes and a standardized question design for questioning against the indexes.
 
Lucene was initially written in Java as a part of the Apache project. Zend_Search_Lucene is a PHP usage that brings full binary similarity with Java Lucene.
Zend\Authentication\Adapter\DbTable provides the ability to authenticate against credentials stored in a database table. Because Zend\Authentication\Adapter\DbTable requires an instance of Zend\Db\Adapter\Adapter to be passed to its constructor, each instance is bound to a particular database connection. Other configuration options may be set through the constructor and through instance methods, one for each option.
 
The available configuration options include :
 
tableName : This is the name of the database table that contains the authentication credentials, and against which the database authentication query is performed.

identityColumn : This is the name of the database table column used to represent the identity. The identity column must contain unique values, such as a username or e-mail address.

credentialColumn : This is the name of the database table column used to represent the credential. Under a simple identity and password authentication scheme, the credential value corresponds to the password. See also the credentialTreatment option.

credentialTreatment : In many cases, passwords and other sensitive data are encrypted, hashed, encoded, obscured, salted or otherwise treated through some function or algorithm. By specifying a parameterized treatment string with this method, such as ‘MD5(?)‘ or ‘PASSWORD(?)‘, a developer may apply such arbitrary SQL upon input credential data. Since these functions are specific to the underlying RDBMS, check the database manual for the availability of such functions for your database system.

Basic Usage

As explained in the introduction, the Zend\Authentication\Adapter\DbTable constructor requires an instance of Zend\Db\Adapter\Adapter that serves as the database connection to which the authentication adapter instance is bound. First, the database connection should be created.
 
The following code creates an adapter for an in-memory database, creates a simple table schema, and inserts a row against which we can perform an authentication query later. This example requires the PDO SQLite extension to be available :
 
use Zend\Db\Adapter\Adapter as DbAdapter;

// Create a SQLite database connection
$dbAdapter = new DbAdapter(array(
                'driver' => 'Pdo_Sqlite',
                'database' => 'path/to/sqlite.db'
            ));

// Build a simple table creation query
$sqlCreate = 'CREATE TABLE [users] ('
           . '[id] INTEGER  NOT NULL PRIMARY KEY, '
           . '[username] VARCHAR(50) UNIQUE NOT NULL, '
           . '[password] VARCHAR(32) NULL, '
           . '[real_name] VARCHAR(150) NULL)';

// Create the authentication credentials table
$dbAdapter->query($sqlCreate);

// Build a query to insert a row for which authentication may succeed
$sqlInsert = "INSERT INTO users (username, password, real_name) "
           . "VALUES ('my_username', 'my_password', 'My Real Name')";

// Insert the data
$dbAdapter->query($sqlInsert);
Zend\Authentication\Adapter\Http provides a mostly-compliant implementation of RFC-2617, Basic and Digest HTTP Authentication. Digest authentication is a method of HTTP authentication that improves upon Basic authentication by providing a way to authenticate without having to transmit the password in clear text across the network.
 
Major Features :
 
* Supports both Basic and Digest authentication.
* Issues challenges in all supported schemes, so client can respond with any scheme it supports.
* Supports proxy authentication.
* Includes support for authenticating against text files and provides an interface for authenticating against other sources, such as databases.

There are a few notable features of RFC-2617 that are not implemented yet :
 
* Nonce tracking, which would allow for “stale” support, and increased replay attack protection.
* Authentication with integrity checking, or “auth-int”.
* Authentication-Info HTTP header.
Zend\Authentication\Validator\Authentication provides the ability to utilize a validator for an InputFilter in the instance of a Form or for single use where you simply want a true/false value and being able to introspect the error.
 
The available configuration options include :
 
adapter : This is an instance of Zend\Authentication\Adapter.

identity : This is the identity or name of the identity in the passed in context.

credential : This is the credential or the name of the credential in the passed in context.

service : This is an instance of Zend\Authentication\AuthenticationService


Basic Usage : 

use Zend\Authentication\AuthenticationService;
use Zend\Authentication\Validator\Authentication as AuthenticationValidator;

$service   = new AuthenticationService();
$adapter   = new My\Authentication\Adapter();
$validator = new AuthenticationValidator(array(
    'service' => $service,
    'adapter' => $adapter,
));

$validator->setCredential('myCredentialContext');
$validator->isValid('myIdentity', array(
     'myCredentialContext' => 'myCredential',
));
Barcode objects allow you to generate barcodes independently of the rendering support. After generation, you can retrieve the barcode as an array of drawing instructions that you can provide to a renderer.
 
Objects have a large number of options. Most of them are common to all objects. These options can be set in three ways:
 
* As an array or a Traversable object passed to the constructor.
* As an array passed to the setOptions() method.
* Via individual setters for each configuration type.

Different ways to parameterize a barcode object
use Zend\Barcode\Object;

$options = array('text' => 'ZEND-FRAMEWORK', 'barHeight' => 40);

// Case 1: constructor
$barcode = new Object\Code39($options);

// Case 2: setOptions()
$barcode = new Object\Code39();
$barcode->setOptions($options);

// Case 3: individual setters
$barcode = new Object\Code39();
$barcode->setText('ZEND-FRAMEWORK')
        ->setBarHeight(40);
Renderers have some common options. These options can be set in three ways:
 
* As an array or a Traversable object passed to the constructor.
* As an array passed to the setOptions() method.
* As discrete values passed to individual setters.
 
Different ways to parameterize a renderer object
use Zend\Barcode\Renderer;

$options = array('topOffset' => 10);

// Case 1
$renderer = new Renderer\Pdf($options);

// Case 2
$renderer = new Renderer\Pdf();
$renderer->setOptions($options);

// Case 3
$renderer = new Renderer\Pdf();
$renderer->setTopOffset(10);
The callback cache pattern caches calls of non specific functions and methods given as a callback.
 
Quick Start :  For instantiation you can use the PatternFactory or do it manual:
use Zend\Cache\PatternFactory;
use Zend\Cache\Pattern\PatternOptions;

// Via the factory:
$callbackCache = PatternFactory::factory('callback', array(
    'storage'      => 'apc',
    'cache_output' => true,
));

// OR, the equivalent manual instantiation:
$callbackCache = new \Zend\Cache\Pattern\CallbackCache();
$callbackCache->setOptions(new PatternOptions(array(
    'storage'      => 'apc',
    'cache_output' => true,
)));

 

Option Data Type Default Value Description
storage string array Zend\Cache\Storage\StorageInterface <none> The storage to write/read cached data
cache_output boolean true Cache output of callback
The ObjectCache pattern is an extension to the CallbackCache pattern. It has the same methods but instead it generates the internally used callback in base of the configured object and the given method name.
 
Quick Start : Instantiating the object cache pattern
use Zend\Cache\PatternFactory;

$object      = new stdClass();
$objectCache = PatternFactory::factory('object', array(
    'object'  => $object,
    'storage' => 'apc'
));

Configuration Options :

Option Data Type Default Value Description
storage string array Zend\Cache\Storage\StorageInterface <none> The storage to write/read cached data
object object <none> The object to cache methods calls of
object_key null string <Class name of object> A hopefully unique key of the object
cache_output boolean true Cache output of callback
cache_by_default boolean true Cache method calls by default
object_cache_methods array [] List of methods to cache (If cache_by_default is disabled)
object_non_cache_methods array [] List of methods to no-cache (If cache_by_default is enabled)
object_cache_magic_properties boolean false Cache calls of magic object properties
The AdapterInterface : All CAPTCHA adapters implement Zend\Captcha\AdapterInterface, which looks like the following :
namespace Zend\Captcha;

use Zend\Validator\ValidatorInterface;

interface AdapterInterface extends ValidatorInterface
{
    public function generate();

    public function setName($name);

    public function getName();

    // Get helper name used for rendering this captcha type
    public function getHelperName();
}
The name setter and getter are used to specify and retrieve the CAPTCHA identifier. The most interesting methods are generate() and render(). generate() is used to create the CAPTCHA token. This process typically will store the token in the session so that you may compare against it in subsequent requests. render() is used to render the information that represents the CAPTCHA, be it an image, a figlet, a logic problem, or some other CAPTCHA.
In Zend Framework, We need to disable layout when we make an AJAX request to fetch data with the help of the following code.
$this->_helper->layout()->disableLayout();  
$this->_helper->viewRenderer->setNoRender(true);  
Service manager registration is a set of methods that are used to register a component. Here are some important methods, such as:
 
* Factory method
* Abstract factory method
* Initialize method
* Delegator factory method
Zend Engine is a set of various components used internally by PHP as a compiler and runs engine time. The most important Zend Engine part is the Zend Virtual Machine, which stabilizes the Zend Executor components and the Zend Compiler. PHP scripts are loaded into memory and organized into Zend opcodes.
Routing is the process of taking a URI endpoint (that part of the URI which comes after the base URL) and decomposing it into parameters to determine which module, controller, and action of that controller should receive the request.
 
These values of the module, controller, action, and other parameters are packaged into a Zend_Controller_Request_Http object which is then processed by Zend_Controller_Dispatcher_Standard.
 
Routing occurs only once when the request is initially received and before the first controller is dispatched. Zend_Controller_Router_Rewrite is the standard framework router.
There are the following types of routing in the Zend framework:
 
Hostname : It is used to match the host part of the URI.
Literal : It is used to match the exact URI.
Method : It is used to match the HTTP method of the incoming request.
Part : It is used to match the part of the URI path segment using custom logic.
Regex : It is used to match the URI path segment by Regex Pattern.
In addition to console abstraction layer Zend Framework 2 provides numerous convenience classes for interacting with the user in console environment. This chapter describes available Zend\Console\Prompt classes and their example usage.
 
All prompts can be instantiated as objects and provide show() method.
use Zend\Console\Prompt;

$confirm = new Prompt\Confirm('Are you sure you want to continue?');
$result = $confirm->show();
if ($result) {
    // the user chose to continue
}
 
There is also a shorter method of displaying prompts, using static prompt() method :
use Zend\Console\Prompt;

$result = Prompt\Confirm::prompt('Are you sure you want to continue?');
if ($result) {
    // the user chose to continue
}
Zend Framework 2 provides console abstraction layer, which works around various bugs and limitations in operating systems. It handles displaying of colored text, retrieving console window size, charset and provides basic line drawing capabilities.
 
Retrieving console adapter : If you are using MVC controllers you can obtain Console adapter instance using Service Manager.
namespace Application;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\Console\Adapter\AdapterInterface as Console;
use Zend\Console\Exception\RuntimeException;

class ConsoleController extends AbstractActionController
{
    public function testAction()
    {
        $console = $this->getServiceLocator()->get('console');
        if (!$console instanceof Console) {
            throw new RuntimeException('Cannot obtain console adapter. Are we running in a console?');
        }
    }
}
 
If you are using Zend\Console without MVC, we can get adapter using the following code :
use Zend\Console\Console;
use Zend\Console\Exception\RuntimeException as ConsoleException;

try {
    $console = Console::getInstance();
} catch (ConsoleException $e) {
    // Could not get console adapter - most likely we are not running inside a console window.
}
The Zend\Console\Getopt class helps command-line applications to parse their options and arguments.
 
Users may specify command-line arguments when they execute your application. These arguments have meaning to the application, to change the behavior in some way, or choose resources, or specify parameters. Many options have developed customary meaning, for example --verbose enables extra output from many applications. Other options may have a meaning that is different for each application. For example, -c enables different features in grep, ls, and tar.
 
Below are a few definitions of terms. Common usage of the terms varies, but this documentation will use the definitions below.
 
* “argument” : a string that occurs on the command-line following the name of the command. Arguments may be options or else may appear without an option, to name resources on which the command operates.
 
* “option” : an argument that signifies that the command should change its default behavior in some way.
 
* “flag” : the first part of an option, identifies the purpose of the option. A flag is preceded conventionally by one or two dashes (- or --). A single dash precedes a single-character flag or a cluster of single-character flags. A double-dash precedes a multi-character flag. Long flags cannot be clustered.
 
* “parameter” : the secondary part of an option; a data value that may accompany a flag, if it is applicable to the given option. For example, many commands accept a --verbose option, but typically this option has no parameter. However, an option like --user almost always requires a following parameter.
 
A parameter may be given as a separate argument following a flag argument, or as part of the same argument string, separated from the flag by an equals symbol (=). The latter form is supported only by long flags. For example, -u username, --user username, and --user=username are forms supported by Zend\Console\Getopt.
 
*  “cluster” : multiple single-character flags combined in a single string argument and preceded by a single dash. For example, “ls -1str” uses a cluster of four short flags. This command is equivalent to “ls -1 -s -t -r”. Only single-character flags can be clustered. You cannot make a cluster of long flags.
 
For example, in mysql --user=root mydatabase, mysql is a command, --user=root is an option, --user is a flag, root is a parameter to the option, and mydatabase is an argument but not an option by our definition.
 
Zend\Console\Getopt provides an interface to declare which flags are valid for your application, output an error and usage message if they use an invalid flag, and report to your application code which flags the user specified.
The constructor for the Zend\Console\Getopt class takes from one to three arguments. The first argument declares which options are supported by your application. This class supports alternative syntax forms for declaring the options. See the sections below for the format and usage of these syntax forms.
 
The constructor takes two more arguments, both of which are optional. The second argument may contain the command-line arguments. This defaults to $_SERVER['argv'].
 
The third argument of the constructor may contain an configuration options to customize the behavior of Zend\Console\Getopt. See Adding Configuration for reference on the options available.
 
Declaring Options with the Short Syntax : Zend\Console\Getopt supports a compact syntax similar to that used by GNU Getopt (see http://www.gnu.org/software/libc/manual/html_node/Getopt.html. This syntax supports only single-character flags. In a single string, you type each of the letters that correspond to flags supported by your application. A letter followed by a colon character (:) indicates a flag that requires a parameter.
 
Using the Short Syntax : 

$opts = new Zend\Console\Getopt('abp:');
First create directory 'library', and put 'Zend' directory in it. Now you should add library to your include path. Edit index.php file :
$includePath = array();  
$includePath[] = '.';  
$includePath[] = './../application';  
$includePath[] = './../library';  
$includePath[] = get_include_path();  
$includePath = implode(PATH_SEPARATOR,$includePath);  
set_include_path($includePath);
In the Zend framework, there are various methods of Cookies class that are listed below :

addCookie(uri) : It is used to add a cookie into the request object of the given URI.

getCookie(cookieName, $cookieForm) : It is used to get the cookie, $cookieName available in the given URI.

fromResponse(uri) : It is used to extract cookies from the response object of the given URI.

isEmpty() : It is used to find whether the given Cookie object has any cookie or not.

reset() : It is used to clear all the cookies in the given URI.
The file element needs a special file decorator, which is added by default. When you set your own decorators for file elements, you delete the default decorators. For example :
$element->setDecorators(array(  
array('ViewHelper'),  
array('Errors')  
));  
You should use a File decorator instead of the ViewHelper for the file element, as shown below :
$element->setDecorators(array(  
array('File'),  
array('Errors')  
));​
  
The CLA protects all users, including individuals, small and medium businesses, and large corporations. By having a CLA in place, we mitigate the risk that companies who claim intellectual property infringement may demand royalties or fees from users of Zend Framework, whether individuals or companies.
 
This is especially important for companies basing their business or products on Zend Framework. The Zend Framework CLA helps to ensure that code and other IP in Zend Framework remain free.
In Zend, you can protect a website from sql injection using select query :
$this->getAdapter()->quote();  
$select->where(" = ",);  
$select->where(" = ? ",);
The EventManager is a component designed for the following use cases:
 
* Implementing simple subject/observer patterns.
* Implementing Aspect-Oriented designs.
* Implementing event-driven architectures.

The basic architecture allows you to attach and detach listeners to named events, both on a per-instance basis as well as via shared collections; trigger events; and interrupt execution of listeners.
 
Quick Start : Typically, you will compose an EventManager instance in a class.
use Zend\EventManager\EventManagerInterface;
use Zend\EventManager\EventManager;
use Zend\EventManager\EventManagerAwareInterface;

class Foo implements EventManagerAwareInterface
{
    protected $events;

    public function setEventManager(EventManagerInterface $events)
    {
        $events->setIdentifiers(array(
            __CLASS__,
            get_called_class(),
        ));
        $this->events = $events;
        return $this;
    }

    public function getEventManager()
    {
        if (null === $this->events) {
            $this->setEventManager(new EventManager());
        }
        return $this->events;
    }
}
The Zend\Escaper component provides one class, Zend\Escaper\Escaper which in turn, provides five methods for escaping output. Which method to use when, depends on the context in which the outputted data is used. It is up to the developer to use the right methods in the right context.
 
Zend\Escaper\Escaper has the following escaping methods available for each context :
 
escapeHtml : escape a string for the HTML Body context.

escapeHtmlAttr : escape a string for the HTML Attribute context.

escapeJs : escape a string for the Javascript context.

escapeCss : escape a string for the CSS context.

escapeUrl : escape a string for the URI or Parameter contexts.
Available Methods :
TODO
 
Examples : 
TODO
Often, fieldsets or elements in your forms will correspond to other domain objects. In some cases, they may correspond to collections of domain objects. In this latter case, in terms of user interfaces, you may want to add items dynamically in the user interface – a great example is adding tasks to a task list.
The Service Locator design pattern is implemented by the Zend\ServiceManager component. The Service Locator is a service/object locator, tasked with retrieving other objects. Following is the Zend\ServiceManager\ServiceLocatorInterface API :
namespace Zend\ServiceManager;

interface ServiceLocatorInterface
{
    public function get($name);
    public function has($name);
}
* has($name), tests whether the ServiceManager has a named service;
* get($name), retrieves a service by the given name.
Zend\Soap\Server class is intended to simplify Web Services server part development for PHP programmers.
 
It may be used in WSDL or non-WSDL mode, and using classes or functions to define Web Service API.
 
When Zend\Soap\Server component works in the WSDL mode, it uses already prepared WSDL document to define server object behavior and transport layer options.
 
WSDL document may be auto-generated with functionality provided by Zend\Soap\AutoDiscovery component or should be constructed manually using Zend\Soap\Wsdl class or any other XML generating tool.