Session Management

Zend Framework – Session Management ”; Previous Next 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. Install a Session Component Session component can be installed using the Composer as specified below − composer require zendframework/zend-session Session Components Zend framework provides six components to handle session management. All these components have been explained below − ZendSessionContainer − The main API to read and write the session information. ZendSessionSessionManager − It is used to manage the entire lifecycle of a session. ZendSessionStorage − This is used to specify how the session data will be stored in the memory. ZendSessionSaveHandler − It is used to store and retrieve the session data into a physical location like RDBMS, Redis, MangoDB, etc. ZendSessionValidator − This is used to protect session from hijacking by cross-checking initial and subsequent request”s remote address and user agent. ZendSessionConfigSessionConfig − It is used to configure how the session should behave. The default configuration is enough to work with a session. Using the above components, all aspects of a session can be handled easily. Session Component Example Let us adhere to the following points to create a new page to understand a session in Zend framework. By default, it is enough to create an instance of a Container class to manage sessions. Create a new action, sessionAction in TutorialController. Initialize a Container object. $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++; } Register the count in the ViewModel. Create a template file for – sessionAction, session.phtml in myapp/module/Tutorial/view/tutorial/tutorial/session.phtml and then render the count value. Refreshing the page will increase the value of count in the session. The complete listing is as follows − TutorialController.php public function sessionAction() { $c = new Container(); if (!isset($c->count)) { $c->count = 0; } else { $c->count++; } $view = new ViewModel([ ”count” => $c->count, ]); return $view; } session.pthml Session data, COUNT = <?= $this->count ?> Sample Result Session data, Count = 5 Print Page Previous Next Advertisements ”;

Zend Framework – Concepts

Zend Framework – Concepts ”; Previous Next 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 Framework provides three most important components, which are − 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. Module Manager − Ability to convert a collection of PHP classes with similar functionality into a single unit called as a module. The newly created modules can be used, maintained and configured as a single unit. We will cover these concepts in detail in the subsequent chapters. Print Page Previous Next Advertisements ”;

Zend Framework – Ajax

Zend Framework – Ajax ”; Previous Next 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. Install json component The Zend json component can be installed using the Composer command as specified below − composer require zendframework/zend-json Concept Zend framework provides two methods to easily write an AJAX enabled web application. They are as follows − The isXmlHttpRequest() method in the Request object – If an AJAX request is made, the request object”s isXmlHttpRequest() method returns true, otherwise false. This method is used to handle an AJAX request properly in the server side. if ($request->isXmlHttpRequest()) { // Ajax request } else { // Normal request } The Zend/View/Model/JsonModel – The JsonModel is an alternative for ViewModel to be used exclusively for AJAX and the REST API scenarios. The JsonModel along with JsonStrategy (to be configured in the module”s view manager block) encodes the model data into Json and returns it as a response instead of views (phtml). AJAX – Working Example Let us add a new ajax page, ajax in the tutorial module and fetch the book information asynchronously. To do this, we should adhere to the following steps. Step 1: Add JsonStrategy in module configuration Update the view manager block in the tutorial module configuration file – myapp/module/Tutorial/config/module.config.php. Then, JsonStrategy will work with JsonModel to encode and send the json data. ”view_manager” => [ ”template_map” => array (”layout/layout” => __DIR__ . ”/../view/layout/newlayout.phtml”), ”template_path_stack” => [ ”tutorial” => __DIR__ . ”/../view”, ], ”strategies” => array(”ViewJsonStrategy”,), ], Step 2: Add ajaxAction method in the TutorialController.php Add the ajaxAction method in the TutorialController.php with the following code − public function ajaxAction() { $data = $this->bookTable->fetchAll(); $request = $this->getRequest(); $query = $request->getQuery(); 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; } $view = new JsonModel($jsonData); $view->setTerminal(true); } 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. The $query->get(”showJson”) == 1 is used for debugging purposes. Just add showJson=1 in the url and the page will display the json data. Step 3: Add ajax.phtml Now, add the view script ajax.phtml for the ajaxAction method. This page will have a link with the label – Load book information. 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. The complete code listing is as follows − <a id = “loadbook” href = “#”>Load book information</a> </br> </br> <table class = “table”> <tbody id = “book”> </tbody> </table> <script language = “javascript”> $(document).ready(function(){ $(“#loadbook”).on(“click”, function(event){ $.ajax({ 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> Step 4: Run the application Finally, run the application − http://localhost:8080/tutorial/ajax and click the Load book information link. The result will be as shown below − Ajax Page − Ajax Page with Book Information Ajax page with debugging information Print Page Previous Next Advertisements ”;

Models & Database

Zend Framework – Models & Database ”; Previous Next In this chapter, we will discuss regarding the various models and the database of the Zend Framework. Models in Zend Framework A Model defines the logical data representation of the application. For example, in a shopping cart application – Product, Customer, Cart and Orders are models. They define the properties of the entity it holds. Some of the concepts of models are as follows − 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. Let us take a look at a simple model – MyModel <?php namespace TutorialModel; class Book { public $id; public $author; public $title; } Database in Zend Framework Zend framework provides a simple and feature-rich class, ZendDbTableGatewayTableGateway to find, insert, update and delete data from a database table. Let us see how to connect the MySqlservice via PHP”s PDO driver in Zend framework through the following steps. Step 1: Create database in MySQL Create database tutorials in the local MySQL server. We can use phpmyadmin or any other MySQL GUI tools for this purpose. Let us use the MySQL client in the command prompt. Connect to the mysql server and run the following command to create the tutorial database. create database tutorials Step 2: Create table in the tutorials db Let us now create a database book in the tutorials db using the following SQL command. use tutorials; CREATE TABLE book ( id int(11) NOT NULL auto_increment, author varchar(100) NOT NULL, title varchar(100) NOT NULL, PRIMARY KEY (id) ); Step 3: Populate data in the book table Populate the book table with sample data. Use the following SQL command. 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”); Step 4: Update Database Connection Update the global configuration file, which is – myapp/config/autoload/global.php with the necessary database drive information. <?php return array( ”db” => array( ”driver” => ”Pdo”, ”dsn” => ”mysql:dbname = tutorials;host = localhost”, ”driver_options” => array( PDO::MYSQL_ATTR_INIT_COMMAND => ”SET NAMES ”UTF8”” ), ), ”service_manager” => array( ”factories” => array( ”ZendDbAdapterAdapter” => ”ZendDbAdapterAdapterServiceFactory”, ), ), ); Step 5: Update Database Credentials Update the database credentials in the local configuration file, which is – myapp/config/autoload/local.php. In this way, we can separate the local and live database connection credentials. <?php return array( ”db” => array( ”username” => ”<user_name>”, ”password” => ”<password>”, ), ); Step 6: Create Model for Book Let us create a Model, Book in our module src directory. Generally, models are grouped under the Model folder – /myapp/module/Tutorial/src/Model/Book.php. <?php namespace TutorialModel; class Book { public $id; public $author; public $title; } Step 7: Implement exchangeArray in the book model The TableGateway interacts with a model through the exchangeArray function. The standard argument of the exchangeArray function is the database result set stored as the PHP array. Using the exchangeArrayfunction, a model”s property can be easily synced with the corresponding database table. Update the model, Book as shown below − <?php namespace TutorialModel; class Book { public $id; public $author; public $title; public function exchangeArray($data) { $this->id = (!empty($data[”id”])) ? $data[”id”] : null; $this->Author = (!empty($data[”author”])) ? $data[”author”] : null; $this->Title = (!empty($data[”title”])) ? $data[”title”] : null; } } Step 8: Use TableGateway to fetch book Create a class, BookTable to fetch book information from the database. Create the class, BookTable in the Model folder itself. <?php namespace TutorialModel; use ZendDbTableGatewayTableGatewayInterface; class BookTable { protected $tableGateway; public function __construct(TableGatewayInterface $tableGateway) { $this->tableGateway = $tableGateway; } public function fetchAll() { $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. Step 9: Configure BookTable class Update the tutorial module, Module.php with the getServiceConfig() method. <?php namespace Tutorial; use ZendDbAdapterAdapterInterface; use ZendDbResultSetResultSet; use ZendDbTableGatewayTableGateway; use ZendModuleManagerFeatureConfigProviderInterface; class Module implements ConfigProviderInterface { public function getConfig() { return include __DIR__ . ”/../config/module.config.php”; } public function getServiceConfig() { return [ ”factories” => [ ModelBookTable::class => function ($container) { $tableGateway = $container->get(ModelBookTableGateway::class); $table = new ModelBookTable($tableGateway); return $table; }, ModelBookTableGateway::class => function ($container) { $dbAdapter = $container->get(AdapterInterface::class); $resultSetPrototype = new ResultSet(); $resultSetPrototype->setArrayObjectPrototype(new ModelBook()); return new TableGateway(”book”, $dbAdapter, null, $resultSetPrototype); }, ], ]; } } 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. Another item, ModelBookTableGateway::class is the TableGateway object specialized for the Book model and is a dependency of the BookTable. Step 10: Update TutorialController Configuration We need the BookTable service in the tutorial controller to fetch the book information. To get the BookTable service, register it as constructor dependency in the TutorialController. 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” => [ ControllerTutorialController::class => function($container) { return new ControllerTutorialController( $container->get(ModelBookTable::class) ); }, ], ], Step 11: Update Tutorial Controller This is done by adhering

Zend Framework – MVC Architecture

Zend Framework – MVC Architecture ”; Previous Next 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. The short description of the MVC Components is as follows 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. Print Page Previous Next Advertisements ”;

Zend Framework – Creating Module

Zend Framework – Creating a Module ”; Previous Next 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. Create a new PHP class named Module inside the –myapp/module/Tutorial/src/ directory and implement the ConfigProviderInterface. Set Tutorial as the namespace for the Module class. Write a public function getConfig in the Module class and return the configuration file for the Tutorial Module. The complete code for the Module class is as follows − <?php namespace Tutorial; use ZendModuleManagerFeatureConfigProviderInterface; class Module implements ConfigProviderInterface { public function getConfig() { return include __DIR__ . ”/../config/module.config.php”; } } 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 The composer command will do necessary change to the application and show the logs in the command prompt as shown below − Loading composer repositories with package information Updating dependencies (including require-dev) – Removing zendframework/zend-component-installer (0.3.0) – Installing zendframework/zend-component-installer (0.3.1) Downloading: 100% – Removing zendframework/zend-stdlib (3.0.1) – Installing zendframework/zend-stdlib (3.1.0) Loading from cache – Removing zendframework/zend-eventmanager (3.0.1) – Installing zendframework/zend-eventmanager (3.1.0) Downloading: 100% – Removing zendframework/zend-view (2.8.0) – Installing zendframework/zend-view (2.8.1) Loading from cache – Removing zendframework/zend-servicemanager (3.1.0) – Installing zendframework/zend-servicemanager (3.2.0) Downloading: 100% – Removing zendframework/zend-escaper (2.5.1) – Installing zendframework/zend-escaper (2.5.2) Loading from cache – Removing zendframework/zend-http (2.5.4) – Installing zendframework/zend-http (2.5.5) Loading from cache – Removing zendframework/zend-mvc (3.0.1) – Installing zendframework/zend-mvc (3.0.4) Downloading: 100% – Removing phpunit/phpunit (5.7.4) – Installing phpunit/phpunit (5.7.5) Downloading: 100% Writing lock file Generating autoload files Create the module configuration file, “module.config.php” at /config/ with the following code − <?php namespace Tutorial; use ZendServiceManagerFactoryInvokableFactory; use ZendRouterHttpSegment; return [ ”controllers” => [ ”factories” => [ControllerTutorialController::class => InvokableFactory::class,], ], ”view_manager” => [ ”template_path_stack” => [”tutorial” => __DIR__ . ”/../view”,], ], ]; The configuration file has three parts and they are as follows − Controller configuration − Specify the controllers available inside the Module. Routing configuration − Specify how the controllers in the module should be resolved into URLs. View configuration − Specify the configuration related to view the engine such as the location of views, etc. Configure the Tutorial module in the application level configuration file – myapp/config/modules.config.php. return [”ZendRouter”, ”ZendValidator”, ”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. Print Page Previous Next Advertisements ”;

Skeleton Application

Zend Framework – Skeleton Application ”; Previous Next Let us create a skeleton application using the Zend Framework MVC layer and module systems. Installation using Composer The easiest way to create a new Zend Framework project is to use a Composer. It is defined as below − $ cd /path/to/install $ composer create-project -n -sdev zendframework/skeleton-application myapp You would see the following result on your screen − Installing zendframework/skeleton-application (dev-master 941da45b407e4f09e264f000fb537928badb96ed) – Installing zendframework/skeleton-application (dev-master master) Cloning master Created project in myapp Loading composer repositories with package information Installing dependencies (including require-dev) from lock file – Installing zendframework/zend-component-installer (0.3.0) Loading from cache – Installing zendframework/zend-stdlib (3.0.1) Loading from cache – Installing zendframework/zend-config (2.6.0) Loading from cache – Installing zendframework/zend-loader (2.5.1) Loading from cache – Installing zendframework/zend-eventmanager (3.0.1) Loading from cache – Installing zendframework/zend-view (2.8.0) Loading from cache – Installing container-interop/container-interop (1.1.0) Loading from cache – Installing zendframework/zend-servicemanager (3.1.0) Loading from cache – Installing zendframework/zend-validator (2.8.1) Loading from cache – Installing zendframework/zend-escaper (2.5.1) Loading from cache – Installing zendframework/zend-uri (2.5.2) Loading from cache – Installing zendframework/zend-http (2.5.4) Loading from cache – Installing zendframework/zend-router (3.0.2) Loading from cache – Installing zendframework/zend-modulemanager (2.7.2) Loading from cache – Installing zendframework/zend-mvc (3.0.1) Loading from cache – Installing zendframework/zend-skeleton-installer (0.1.3) Loading from cache – Installing zfcampus/zf-development-mode (3.0.0) Loading from cache zendframework/zend-config suggests installing zendframework/zend-filter (ZendFilter component) zendframework/zend-config suggests installing zendframework/zend-i18n (ZendI18n component) zendframework/zend-config suggests installing zendframework/zend-json (ZendJson to use the Json reader or writer classes) zendframework/zend-view suggests installing zendframework/zend-authentication (ZendAuthentication component) zendframework/zend-view suggests installing zendframework/zend-feed (ZendFeed component) zendframework/zend-view suggests installing zendframework/zend-filter (ZendFilter component) zendframework/zend-view suggests installing zendframework/zend-i18n (ZendI18n component) zendframework/zend-view suggests installing zendframework/zend-json (ZendJson component) zendframework/zend-view suggests installing zendframework/zend-navigation (ZendNavigation component) zendframework/zend-view suggests installing zendframework/zend-paginator (ZendPaginator component) zendframework/zend-view suggests installing zendframework/zend-permissions-acl (ZendPermissionsAcl component) zendframework/zend-servicemanager suggests installing ocramius/proxy-manager (ProxyManager 1.* to handle lazy initialization of services) zendframework/zend-validator suggests installing zendframework/zend-db (ZendDb component) zendframework/zend-validator suggests installing zendframework/zend-filter (ZendFilter component, required by the Digits validator) zendframework/zend-validator suggests installing zendframework/zend-i18n (ZendI18n component to allow translation of validation error messages as well as to use the various Date validators) zendframework/zend-validator suggests installing zendframework/zend-i18nresources (Translations of validator messages) zendframework/zend-validator suggests installing zendframework/zend-math (ZendMath component) zendframework/zend-validator suggests installing zendframework/zend-session (ZendSession component) zendframework/zend-router suggests installing zendframework/zend-i18n (^2.6, if defining translatable HTTP path segments) zendframework/zend-modulemanager suggests installing zendframework/zend-console (ZendConsole component) zendframework/zend-mvc suggests installing zendframework/zend-json ((^2.6.1 || ^3.0) To auto-deserialize JSON body content in AbstractRestfulController extensions, when json_decode is unavailable) zendframework/zend-mvc suggests installing zendframework/zend-mvc-console (zend-mvc-console provides the ability to expose zend-mvc as a console application) zendframework/zend-mvc suggests installing zendframework/zend-mvc-i18n (zendmvc-i18n provides integration with zend-i18n, including a translation bridge and translatable route segments) zendframework/zend-mvc suggests installing zendframework/zend-mvc-pluginfileprg (To provide Post/Redirect/Get functionality around forms that container file uploads) zendframework/zend-mvc suggests installing zendframework/zend-mvc-pluginflashmessenger (To provide flash messaging capabilities between requests) zendframework/zend-mvc suggests installing zendframework/zend-mvc-pluginidentity (To access the authenticated identity (per zend-authentication) in controllers) zendframework/zend-mvc suggests installing zendframework/zend-mvc-plugin-prg (To provide Post/Redirect/Get functionality within controllers) zendframework/zend-mvc suggests installing zendframework/zend-psr7bridge ((^0.2) To consume PSR-7 middleware within the MVC workflow) zendframework/zend-mvc suggests installing zendframework/zend-servicemanager-di (zend-servicemanager-di provides utilities for integrating zend-di and zendservicemanager in your zend-mvc application) Generating autoload files Removing optional packages from composer.json Updating composer.json Removing zendframework/zend-skeleton-installer… – Removing zendframework/zend-skeleton-installer (0.1.3) Removed plugin zendframework/zend-skeleton-installer. Removing from composer.json Complete! > zf-development-mode enable You are now in development mode. 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 Then you would see the following response − > php -S 0.0.0.0:8080 -t public/ public/index.php 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. $ composer require –dev zendframework/zend-test It will produce the following response − Using version ^3.0 for zendframework/zend-test ./composer.json has been updated Loading composer repositories with package information Updating dependencies (including require-dev) – Installing zendframework/zend-dom (2.6.0) Loading from cache – Installing zendframework/zend-console (2.6.0) Loading from cache – Installing sebastian/version (2.0.1) Loading from cache – Installing symfony/yaml (v3.2.1) Downloading: 100% – Installing sebastian/resource-operations (1.0.0) Loading from cache – Installing sebastian/recursion-context (2.0.0) Loading from cache – Installing sebastian/object-enumerator (2.0.0) Loading from cache – Installing sebastian/global-state (1.1.1) Loading from cache – Installing sebastian/exporter (2.0.0) Loading from cache – Installing sebastian/environment (2.0.0) Loading from cache – Installing sebastian/diff (1.4.1) Loading from cache – Installing sebastian/comparator (1.2.2) Loading from cache – Installing phpunit/php-text-template (1.2.1) Loading from cache – Installing doctrine/instantiator (1.0.5) Loading from cache – Installing phpunit/phpunit-mock-objects (3.4.3) Downloading: 100% – Installing phpunit/php-timer (1.0.8) Loading from cache – Installing phpunit/php-file-iterator (1.4.2) Loading from cache – Installing sebastian/code-unit-reverse-lookup (1.0.0) Loading from cache – Installing phpunit/php-token-stream (1.4.9) Loading from cache – Installing phpunit/php-code-coverage (4.0.4) Downloading: 100% – Installing webmozart/assert (1.2.0) Loading from cache – Installing phpdocumentor/reflection-common (1.0) Loading from cache – Installing phpdocumentor/type-resolver (0.2.1) Loading from cache – Installing phpdocumentor/reflection-docblock (3.1.1) Loading from cache – Installing phpspec/prophecy (v1.6.2) Loading from cache – Installing myclabs/deep-copy (1.5.5) Loading from cache – Installing phpunit/phpunit (5.7.4) Downloading: 100% – Installing zendframework/zend-test (3.0.2) Loading from cache zendframework/zend-console suggests installing zendframework/zend-filter (To support DefaultRouteMatcher usage) symfony/yaml suggests installing symfony/console (For validating YAML files using the lint command) sebastian/global-state suggests installing ext-uopz (*) phpunit/phpunit-mock-objects suggests installing ext-soap (*) phpunit/php-code-coverage suggests installing ext-xdebug (>=2.4.0) phpunit/phpunit suggests installing phpunit/php-invoker (~1.1) phpunit/phpunit suggests installing ext-xdebug (*) zendframework/zend-test suggests installing zendframework/zend-mvc-console (^1.1.8, to test MVC <-> console integration) Writing lock file Generating autoload files Now the testing support is enabled so you can run the test using the following command. $ ./vendor/bin/phpunit Apache Web Server Hosting the Zend Framework based application in the production environment is very simple and straight-forward. Just create a VirtualHost in the Apache configuration file and point the DocumentRoot to the Public folder of the Zend Framework application. A sample configuration (myapp) is given below − <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>

Zend Framework – Event Manager

Zend Framework – Event Manager ”; Previous Next 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. Install Event Manager The event manager can be installed using the Composer as specified below − composer require zendframework/zend-eventmanager Concepts of the Event Manager The core concepts of the event manager are as follows − Event − Event is arbitrarily named action, say greet. 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. EventManagerAwareInterface − For a class to support event based programming, it needs to implement the EventManagerAwareInterface. It provides two methods, setEventManager and getEventManager to get and set the event manager. Example Let us write a simple PHP console application to understand the event manager concept. Follow the steps given below. Create a folder “eventapp”. Install zend-eventmanager using the composer. Create a PHP file Greeter.php inside the “eventapp” folder. Create class Greeter and implement the EventManagerAwareInterface. require __DIR__ . ”/vendor/autoload.php”; class Greeter implements EventManagerAwareInterface { // code } Here, require is used to autoload all composer installed components. Write the setEventManager method in class Greeter as shown below − public function setEventManager(EventManagerInterface $events) { $events->setIdentifiers([ __CLASS__, get_called_class(),]); $this->events = $events; return $this; } 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 − public function getEventManager() { if (null === $this->events) { $this->setEventManager(new EventManager()); } return $this->events; } 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. Write a method, greet, in class Greeter. public function greet($message) { printf(“”%s” from classn”, $message); $this->getEventManager()->trigger(__FUNCTION__, $this, $message ]); } 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 = new Greeter(); $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 %sn”, $event_name, $target_name, $params_json); }); The listener callback just prints the name of the event, target and the supplied parameters. The complete listing of the Greeter.php is as follows − <?php require __DIR__ . ”/vendor/autoload.php”; use ZendEventManagerEventManagerInterface; use ZendEventManagerEventManager; use ZendEventManagerEventManagerAwareInterface; class Greeter implements EventManagerAwareInterface { protected $events; public function setEventManager(EventManagerInterface $events) { $events->setIdentifiers([__CLASS__, get_called_class(), ]); $this->events = $events; return $this; } public function getEventManager() { if (null === $this->events) { $this->setEventManager(new EventManager()); } return $this->events; } public function greet($message) { printf(“”%s” from classn”, $message); $this->getEventManager()->trigger(__FUNCTION__, $this, [$message ]); } } $greeter = new Greeter(); $greeter->greet(“Hello”); $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 %sn”, $event_name, $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 − “Hello” from class “Hello” from class “greet” event of class “Greeter” is called. The parameter supplied is [“Hello”] 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. Print Page Previous Next Advertisements ”;

Zend Framework – Module System

Zend Framework – Module System ”; Previous Next The Zend Framework provides a powerful module system. The module system has three components. They are as follows − Module Autoloader − A Module Autoloader is responsible for locating and loading of modules from variety of sources. It can load modules packaged as Phar archives as well. The implementation of the Module Autoloader is located at myapp/vendor/zendframework/zend-loader/src/ModuleAutoloader.php. 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/zendmodulemanager/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. MVC Web Module System The MVC Web Application in the Zend Framework is usually written as Modules. A single website can contain one or more modules grouped by functionality. The recommended structure for MVC-Oriented module is as follows − 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 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. autoload_classmap.php − Returns an array of class name and its corresponding filename. autoload_function.php − Returns a PHP callback. This can utilize classes returned by autoload_classmap.php. autoload_register.php − Registers the PHP callback that is returned by the autoload_function.php. 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. Print Page Previous Next Advertisements ”;

Zend Framework – Introduction

Zend Framework – Introduction ”; Previous Next 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. Zend Framework Features Some of the salient features of Zend Framework is as follows − Pure object oriented web application framework Advanced MVC implementation Supports multi databases including PostgreSQL, SQLite etc., Simple cloud API Session management Data encryption Flexible URI Routing Zend provides RESTful API development support. Code reusable and easier to maintain. Why Zend Framework? What makes the Zend Framework one of the premier frameworks used by PHP developers is that – it provides clean and stable code complete with intellectual property rights. It also makes programming easier. It is fast, easy to learn and convenient framework. Zend supports strong cryptography tools and password hashing techniques. Zend Goals Following are the goals of the Zend Framework. Flexibility Simple and productive Compatibility Extensibility − Programmer can easily extend all the framework classes. Portability − Supports multiple environments Zend Applications The following popular products are developed by using the Zend Framework. McAfee Company website IBM Company website Magento − one of the popular shopping cart website. Advantages of Zend Framework Some of the advantages of the Zend Framework are listed below. Loosely Coupled − Zend provides the option to delete modules or components which we don’t need in the application. Performance − Zend Framework is highly optimized for performance. Zend Framework 3 is 4x faster than its previous version. Security − Framework supports industry standard encryption. 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. Print Page Previous Next Advertisements ”;