Zend Framework – Installation

Zend Framework – Installation ”; Previous Next To install the Zend Framework, we must first install the Composer and the latest version of PHP as shown in the following steps. Install Composer − Zend uses Composer for managing its dependencies, so make sure you have the Composer installed on your machine. If the Composer is not installed, then visit the official website of Composer and install it. Install the latest version of PHP − To get the maximum benefit of Zend Framework, install the latest version of PHP. The minimum required version for the Zend Framework 3 is PHP 5.6 or later. Install Zend Framework Zend Framework can be installed in two ways. They are as follows − Manual installation Composer based installation Let us discuss both these installations in detail. Manual Installation Download the latest version of Zend Framework by visiting the following link – https://framework.zend.com/downloads/archives Extract the content of the downloaded archive file to the folder you would like to keep it. Once you have a copy of Zend Framework available in your local machine, your Zend Framework based web application can access the framework classes. Though there are several ways to achieve this, your PHP include_path needs to contain the path to the Zend Framework classes under the /library directory in the distribution. This method applies to Zend Framework version 2.4 and earlier only. Composer Based Installation To easily install the Zend Framework, use the Composer tool. This is the preferred method to install the latest version of Zend Framework. To install all the components of the Zend Framework, use the following Composer command − $ composer require zendframework/zendframework Each Zend Framework module / component can be installed individually as well. For example, to install the MVC component of the Zend Framework, use the following composer command − $ composer require zendframework/zend-mvc Print Page Previous Next Advertisements ”;

Zend Framework – Service Manager

Zend Framework – Service Manager ”; Previous Next The Zend Framework includes a powerful service locator pattern implementation called zend-servicemanager. Zend framework extensively uses the service manager for all its functionalities. The Service Manager provides a high-level abstraction for the Zend Framework. It also integrates nicely with all the other components of the Zend Framework. Install Service Manager The Service Manager component can be installed using the composer tool. composer require zendframework/zend-servicemanager Example First, all the services need to be registered into the service manager. Once the services are registered into the server manager system, it can be accessed at any time with minimal efforts. The service manager provides a lot of options to register the service. A simple example is as follows − use ZendServiceManagerServiceManager; use ZendServiceManagerFactoryInvokableFactory; use stdClass; $serviceManager = new ServiceManager([ ”factories” => [stdClass::class => InvokableFactory::class,], ]); The above code registers the stdClass into the system using the Factory option. Now, we can get an instance of the stdClass at any time using the get() method of the service manager as shown below. use ZendServiceManagerServiceManager; $object = $serviceManager->get(stdClass::class); The get() method shares the retrieved object and so, the object returned by calling the get() method multiple times is one and the same instance. To get a different instance every time, the service manager provides another method, which is the build() method. use ZendServiceManagerServiceManager; $a = $serviceManager->build(stdClass::class); $b = $serviceManager->build(stdClass::class); Service Manager Registration The service manager provides a set of methods to register a component. Some of the most important methods are as given below − Factory method Abstract factory method Initializer method Delegator factory method We will discuss each of these in detail in the upcoming chapters. Factory Method A factory is basically any callable or any class that implements the FactoryInterface (ZendServiceManagerFactoryFactoryInterface). The FactoryInterface has a single method − public function __invoke(ContainerInterface $container, $requestedName, array $options = null) The arguments details of the FactoryInterface is as follows − container (ContainerInterface) − It is the base interface of the ServiceManager. It provides an option to get other services. requestedName − It is the service name. options − It gives additional options needed for the service. Let us create a simple class implementing the FactoryInterface and see how to register the class. Class Test – Object to be Retrieved use stdClass; class Test { public function __construct(stdClass $sc) { // use $sc } } The Test class depends on the stdClass. Class TestFactory – Class to Initialize Test Object class TestFactory implements FactoryInterface { public function __invoke(ContainerInterface $container, $requestedName, array $options = null) { $dep = $container->get(stdClass::class); return new Test($dep); } } The TestFactory uses a container to retrieve the stdClass, creates the instance of the Test class, and returns it. Registration and Usage of the Zend Framework Let us now understand how to register and use the Zend Framework. serviceManager $sc = new ServiceManager([ ”factories” => [stdClass::class => InvokableFactory::class, Test::class => TestFactory::class] ]); $test = $sc->get(Test::class); The service manager provides a special factory called InvokableFactory to retrieve any class which has no dependency. For example, the stdClass can be configured using the InvokableFactory since the stdClass does not depend on any other class. serviceManager $sc = new ServiceManager([ ”factories” => [stdClass::class => InvokableFactory::class] ]); $stdC = $sc->get(stdClass::class); Another way to retrieve an object without implementing the FactoryInterface or using the InvokableFactory is using the inline method as given below. $serviceManager = new ServiceManager([ ”factories” => [ stdClass::class => InvokableFactory::class, Test::class => function(ContainerInterface $container, $requestedName) { $dep = $container->get(stdClass::class); return new Test($dep); }, ], ]); Abstract Factory Method Sometimes, we may need to create objects, which we come to know only at runtime. This situation can be handled using the AbstractFactoryInterface, which is derived from the FactoryInterface. The AbstractFactoryInterface defines a method to check whether the object can be created at the requested instance or not. If object creation is possible, it will create the object using the __invokemethod of the FactoryInterface and return it. The signature of the AbstractFactoryInterface is as follows − public function canCreate(ContainerInterface $container, $requestedName) Initializer Method The Initializer Method is a special option to inject additional dependency for already created services. It implements the InitializerInterface and the signature of the sole method available is as follows − public function(ContainerInterface $container, $instance) function(ContainerInterface $container, $instance) { if (! $instance instanceof EventManagerAwareInterface) { return; } $instance->setEventManager($container->get(EventManager::class)); } In the above example, the method checks whether the instance is of type EventManagerAwareInterface. If it is of type EventManagerAwareInterface, it sets the event manager object, otherwise not. Since, the method may or may not set the dependency, it is not reliable and produces many runtime issues. Delegator Factory Method Zend Framework supports delegators pattern through DelegatorFactoryInterface. It can be used to decorate the service. The signature of this function is as follows − public function __invoke(ContainerInterface $container, $name, callable $callback, array $options = null ); Here, the $callback is responsible for decorating the service instance. Lazy Services Lazy service is one of those services which will not be fully initialized at the time of creation. They are just referenced and only initialized when it is really needed. One of the best example is database connection, which may not be needed in all places. It is an expensive resource as well as have time-consuming process to create. Zend framework provides LazyServiceFactory derived from the DelegatorFactoryInterface, which can produce lazy service with the help of the Delegator concept and a 3rd party proxy manager, which is called as the ocramius proxy manager. Plugin Manager Plugin Manager extends the service manager and provides additional functionality like instance validation. Zend Framework extensively uses the plugin manager. For example, all the validation services come under the ValidationPluginManager. Configuration Option The service manager provides some options to extend the feature of a service manager. They are shared, shared_by_default and aliases. As we discussed earlier, retrieved objects are shared among requested objects by default and we can use the build() method to get a distinct object. We can also use

Zend Framework – Discussion

Discuss Zend Framework ”; Previous Next Zend is an open source PHP framework. It is pure object-oriented and built around the MVC design pattern. Zend framework contains collection of PHP packages which can be used to develop web applications and services. Zend was started by Andi Gutmans and Zeev Suraski. This tutorial will give you a quick introduction to Zend Framework and make you comfortable with its various components. Print Page Previous Next Advertisements ”;

Email Management

Zend Framework – Email Management ”; Previous Next The Zend Framework provides a separate component called as zend-mail to send email messages. The zend-mail component also provides an option to read and write email messages with attachments both in text and html format. Sending an email in Zend is much easier and simple to configure. Let us go through the email concepts, basic settings, advanced settings such as SMTP transport, etc., in this chapter. Install Mail Component The mail component can be installed using the following Composer command. composer require zendframework/zend-mail Basic Email Configuration A basic email consists of one or more recipients, a subject, a body and a sender. Zend provides ZendMailMessage class to create a new email message. To send an email using the zend-mail, you must specify at least one recipient as well as a message body. The partial code to create a new mail message is as follows − use ZendMail; $mail = new MailMessage(); $mail->setSubject(”Zend email sample”); $mail->setBody(”This is content of the mail message”); $mail->setFrom(”[email protected]”, “sender-name”); $mail->addTo(”[email protected]”, “recipient-name”); Zend provides ZendMailSendmail class to send the mail message. Sendmail uses the php native mail function, mail to send the mail message and we can configure the transport layer using php configuration file. The partial coding using Sendmail is as follow − $transport = new MailTransportSendmail(); $transport->send($mail); The zend-mail provides many transport layer and each may require many additional parameters such as username, password, etc Email Management Methods Some of the notable email management methods are as follows − isValid − Messages without a ‘From’ address is invalid. isValid() : bool setEncoding − Set the message encoding. setEncoding(string $encoding) : void getEncoding − Get the message encoding. getEncoding() : string setHeaders − Compose headers. setHeaders(ZendMailHeaders $headers) : void getHeaders − Access headers collection. getHeaders() : ZendMailHeaders setFrom − Set (overwrite) From addresses. It contains a key/value pairs where the key is the human readable name and the value is the email address. setFrom( string|AddressInterface|array|AddressList|Traversable $emailOrAddressList, string|null $name ) : void addFrom − Add a ‘From’ address. addFrom( string|AddressInterface|array|AddressList|Traversable $emailOrAddressOrList, string|null $name ) : void getFrom − Retrieve list of ‘From’ senders. getFrom() : AddressList setTo – Overwrite the address list in the To recipients. setTo( string|AddressInterface|array|AddressList|Traversable $emailOrAddressList, null|string $name ) : void setSubject − Set the message subject header value. setSubject(string $subject) :void setBody − Set the message body. setBody(null|string|ZendMimeMessage|object $body) : void SMTP Transport Layer The zend-mail provides options to send an email using the SMTP server through the ZendMailTransportSmtpclass. It is like Sendmail except that it has a few additional options to configure the SMTP host, port, username, password, etc. The partial code is as follows − use ZendMailTransportSmtp as SmtpTransport; use ZendMailTransportSmtpOptions; $transport = new SmtpTransport(); $options = new SmtpOptions([ ”name” => ”localhost”, ”host” =>”smtp.gmail.com”, ”port” => 465, ]); $transport->setOptions($options); Here, name − Name of the SMTP host. host − Remote hostname or IP address. port − Port on which the remote host is listening. Mail Concept – Example Let us follow the following points to write a simple php console application to understand the mail concept. Create a folder “mailapp”. Install zend-mail using the composer tool. Create a php file Mail.php inside the “mailapp” folder. Create the message using the ZendMailMessage. $message = new Message(); $message->addTo(”[email protected]”); $message->addFrom(”[email protected]”); $message->setSubject(”Hello!”); $message->setBody(“My first Zend-mail application!”); Create the SMTP transport layer and add the necessary configuration. // Setup SMTP transport using LOGIN authentication $transport = new SmtpTransport(); $options = new SmtpOptions([ ”name” => ”localhost”, ”host” => ”smtp.gmail.com”, // or any SMTP server ”port” => 465, // port on which the SMTP server is listening ”connection_class” => ”login”, ”connection_config” => [ username” => ”<your username>”, ”password” => ”<your password>”, ”ssl” => ”ssl”], ]); $transport->setOptions($options); Send the email using the send method. $transport->send($message); The complete listing, Mail.php is as follows − <?php require __DIR__ . ”/vendor/autoload.php”; use ZendMailMessage; use ZendMailTransportSmtp as SmtpTransport; use ZendMailTransportSmtpOptions; $message = new Message(); $message->addTo(”[email protected]”); $message->addFrom(”[email protected]”); $message->setSubject(”Hello!”); $message->setBody(“My first Zend-mail application!”); // Setup SMTP transport using LOGIN authentication $transport = new SmtpTransport(); $options = new SmtpOptions([ ”name” => ”localhost”, ”host” => ”smtp.gmail.com”, // or any SMTP server ”port” => 465, // port on which the SMTP server is listening ”connection_class” => ”login”, ”connection_config” => [ ”username” => ”<your username>”, ”password” => ”<your password>”, ”ssl” => ”ssl”], ]); $transport->setOptions($options); $transport->send($message); Now, run the application in the command prompt php Mail.php. This will send the mail as configured in the application. Print Page Previous Next Advertisements ”;

Zend Framework – Error Handling

Zend Framework – Error Handling ”; Previous Next Failure of system needs to be handled effectively for the smooth running of the system. Zend Framework comes with a default error trapping that prints and logs the error as they occur. This same error handler is used to catch Exceptions. The Error Handler displays errors when the debug is true and logs the error when the debug is false. Zend Framework has several exception classes and the built-in exception handling will capture any uncaught exception and render a useful page. Default Error Handling We can configure the default error settings in the application configuration file, myapp/module/Application/config/module.config.php. The partial code sample is as follows − ”view_manager” => [ ”display_not_found_reason” => true, ”display_exceptions” => true, ”doctype” => ”HTML5”, ”not_found_template” => ”error/404”, ”exception_template” => ”error/index”, ”template_map” => [ ”layout/layout” => __DIR__ . ”/../view/layout/layout.phtml”, ”application/index/index” => __DIR__ . ”/../view/application/index/index.phtml”, ”error/404” => __DIR__ . ”/../view/error/404.phtml”, ”error/index” => __DIR__ . ”/../view/error/index.phtml”, ], ”template_path_stack” => [ __DIR__ . ”/../view”, ], ], Here, the display_exception, not_found_template, exception_template, error/404 and the error/index are error related configuration items and are self-explanatory. The most important item among these is the error/index. This is the template shown when an exception occurs in the system. We can modify this template, myapp/module/Application/view/error/index.phtml to control the amount of error to be shown. Print Page Previous Next Advertisements ”;

Zend Framework – Quick Guide

Zend Framework – Quick Guide ”; Previous Next Zend Framework – Introduction 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. Zend Framework – Installation To install the Zend Framework, we must first install the Composer and the latest version of PHP as shown in the following steps. Install Composer − Zend uses Composer for managing its dependencies, so make sure you have the Composer installed on your machine. If the Composer is not installed, then visit the official website of Composer and install it. Install the latest version of PHP − To get the maximum benefit of Zend Framework, install the latest version of PHP. The minimum required version for the Zend Framework 3 is PHP 5.6 or later. Install Zend Framework Zend Framework can be installed in two ways. They are as follows − Manual installation Composer based installation Let us discuss both these installations in detail. Manual Installation Download the latest version of Zend Framework by visiting the following link – https://framework.zend.com/downloads/archives Extract the content of the downloaded archive file to the folder you would like to keep it. Once you have a copy of Zend Framework available in your local machine, your Zend Framework based web application can access the framework classes. Though there are several ways to achieve this, your PHP include_path needs to contain the path to the Zend Framework classes under the /library directory in the distribution. This method applies to Zend Framework version 2.4 and earlier only. Composer Based Installation To easily install the Zend Framework, use the Composer tool. This is the preferred method to install the latest version of Zend Framework. To install all the components of the Zend Framework, use the following Composer command − $ composer require zendframework/zendframework Each Zend Framework module / component can be installed individually as well. For example, to install the MVC component of the Zend Framework, use the following composer command − $ composer require zendframework/zend-mvc Zend Framework – Skeleton Application 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

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