Zend Framework – View Layer ”; Previous Next A View Layer is the presentation layer of the MVC application. It separates the application logic from the presentation logic. In a typical PHP web application, all business logic and design are intermixed. Intermixing enables faster development in a small project. But, it fails miserably in large project, where lot of high level architecture is involved. To change the design of the web application, a developer needs to work on the business logic as well. This may be catastrophic resulting in breaking of business logic. Zend Framework provides a well thought, clean, flexible and extendable View layer. The View layer is available as a separate module, Zend/View and integrate fine with Zend/Mvc module. The Zend View Layer is separated into multiple components interacting nicely with each other. Its various components are as follows − Variables Containers − Holds view layer”s data. View Models − Holds Variable Containers and design template. Renderers − Process data and template from View Model and output a design representation, maybe the final html output. Resolvers − Resolves template available in the View Model in such a way that the Renderer can consume. View (ZendViewView) − Maps request to the renderer and then renderer to response. Rendering Strategies − Used by View to map request to renderer. Response Strategies − Used by View to map renderer to response. The view layer, View processes the ViewModel, resolves the template using a Resolver, render it using Rendering Strategy and finally outputs it using the Response Renderer. View Layer Configuration Like the controller, a View layer can be configured in a module”s configuration file called as – module.config.php. The main configuration is to specify where the templates are going to be placed. This can be accomplished by adding the following configuration in the “module.config.php”. ”view_manager” => [ ”template_path_stack” => [”tutorial” => __DIR__ . ”/../view”,], ] By default, the View layer has a default behavior for all its components. For example, a ViewModel resolves the template name of a controller”s action inside the template root by “lowercase-module-name/lowercase-controller-name/lowercase-action-name” rule. However, this can be overridden by the setTemplate() method of the ViewModel. Controllers and View Layer By default, a controller does not need to send any data to the view layer. It is enough to write the template in the proper place. For example, in our example, TutorialController, the template needs to be placed at myapp/module/Tutorial/view/tutorial/tutorial/index.phtml. The index.phtml refers the PHP based template and it will be rendered by the PHPRenderer. There are other renderer’s such as JsonRenderer for json output and FeedRenderer for rss and atom output. The complete listing is as follows − <?php namespace TutorialController; use ZendMvcControllerAbstractActionController; use ZendViewModelViewModel; class TutorialController extends AbstractActionController { public function indexAction() { } } Zend Application Template <div class = “row content”> <h3>This is my first Zend application</h3> </div> Finally, we have successfully completed the Tutorial module and we can access it using url – http://localhost:8080/tutorial. Passing Data to View Layer The simplest way to send the data to a view layer is to use the ViewModel arguments. The changed indexAction method is as follows − public function indexAction() { $view = new ViewModel([ ”message” => ”Hello, Tutorial” ]); return $view; } Now, change the index.phtml file as follows − <div class = “row content”> <h3>This is my first Zend application</h3> <h4><?php echo $this->message?></h4> </div> View Helpers A View Helper is used to write small, atomic functions to be used in templates. Zend framework provides an interface, ZendViewHelperHelperInterface to write standard view helpers. A HelperInterface has just two methods, setView() − This method accepts a ZendViewRendererRendererInterface instance/implementation. getView() − It is used to retrieve that instance. The complete code listing of HelperInterface is as follows − namespace ZendViewHelper; use ZendViewRendererRendererInterface as Renderer; interface HelperInterface { /** * Set the View object * * @param Renderer $view * @return HelperInterface */ public function setView(Renderer $view); /** * Get the View object * * @return Renderer */ public function getView(); } To use a helper in your view script, access it using $this->helperName(). Built-in Helpers Zend Framework provides a lot of inbuilt helper function for various purposes. Some of the View Helpers available in the zend-mvc are as follows − URL URL helper is used to generate the URLs matching the routes defined in the application. The definition of the URL helper is − $this->url($name, $params, $options, $reuseMatchedParameters) For example, in the tutorial module, the route is named as tutorial and it has two parameters action and id. We can use URL helper to generate two different URLs as shown below − <a href = “<? = $this->url(”tutorial”); ?>”>Tutorial Index</a> <a href = “<? = $this->url(”tutorial”, [”action” => ”show”, ”id” =>10]); ?>”> Details of Tutorial #10 </a> The result will be as follows − <a href = “/tutorial”>Tutorial Index</a> <a href = “/tutorial/show/10″> Details of Tutorial #10</a> Placeholder Placeholder helper is used to persist content between view scripts and view instances. It provides option to set data initially and then use it in later stages. For example, we can set, say company name and then use it in all other places. <?php $this->placeholder(”companyname”)->set(“TutorialsPoint”) ?> <?= $this->placeholder(”companyname”); ?> A Placeholder provides some of the advanced options to generate complex content from PHP array and objects. It also has option to capture certain section of the template itself. For example, the following code captures the template result in between and stores it in the productlist placeholder. Class – Product class Product { public $name; public $description; } Controller $p1 = new Product(); $p1->name = ”Car”; $p1->description = ”Car”; $p2 = new Product(); $p2->name = ”Cycle”; $p2->description = ”Cycle”; $view = new ViewModel([”products” => $products]); Template <!– start capture –> <?php $this->placeholder(”productlist”)->captureStart(); foreach ($this->products as $product): ?> <div> <h2><?= $product->name ?></h2> <p><?= $product->description ?></p> </div> <?php endforeach; ?> <?php $this->placeholder(”productlist”)->captureEnd() ?> <!– end capture –> <?= $this->placeholder(”productlist”) ?> Result <div class = “foo”> <h2>Car</h2> <p>Car</p> </div> <div class = “foo”> <h2>Cycle</h2> <p>Cycle</p> </div> Doctype The Doctype
Category: zend Framework
Different Databases
Zend Framework – Different Databases ”; Previous Next As discussed in the last chapter, Zend framework provides a generic way to access the database using the Database Driver concept. Working with a database solely depends on the driver information and so, connecting with different database involves just changing the driver information. Let us now change the book example to connect to the postgresql database with the following steps. Step 1 − Create a database, tutorials in the local postgresql database using the following command − CREATE DATABASE tutorials Step 2 − Add book table. Move to the new database and execute the table creation script. c tutorials CREATE TABLE book ( id SERIAL NOT NULL, author varchar(100) NOT NULL, title varchar(100) NOT NULL, PRIMARY KEY (id) ); Step 3 − Add sample book information using the following script − 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 − Change the driver information in the global.config file. <?php return array ( ”db” => array ( ”driver” => ”Pdo”, ”dsn” => ”pgsql:dbname = tutorials;host = localhost”, ”driver_options” => array ( ), ), ); Step 5 − Change the database credentials in the local.config file. return array ( ”db” => array( ”username” => ”<username>”, ”password” => ”<password>”, ), ); Step 6 − Finally, run the application http://localhost:8080/tutorial. The result is same as the MySQL application. Print Page Previous Next Advertisements ”;
Forms & Validation
Zend Framework – Forms & Validation ”; Previous Next Zend Framework provides a separate component, zend-form to accelerate the form creation and validation process. It connects the model and the view layer. It provides a set of form elements to create full-fledged html form from pre-defined models, an InputFilter class to validate the model against the form and options to bind the data from the form to the model and vice versa. Install Form Component The Zend form component can be installed using the Composer command as specified below − composer require zendframework/zend-form A Zend form framework has three subcomponents to manage the forms. They are as explained below in detail − Elements − Used to define a single html input control mapped to a property in the model. Fieldset − Used to group elements and other fieldset in a nested manner. Form − Used to create an html form and consists of elements and fieldsets. Zend Forms are usually created under the module//src/Form directory. Example Let us now create a simple form to add book into the database. To do this, we should adhere to the following steps − Step 1: Create BookForm Create the “BookForm.php” under the *myapp/module/Tutorial/src/Form” directory. Add the following changes in the file − <?php namespace TutorialForm; use ZendFormForm; class BookForm extends Form { public function __construct($name = null) { parent::__construct(”book”); $this->add(array( ”name” => ”id”, ”type” => ”Hidden”, )); $this->add(array( ”name” => ”author”, ”type” => ”Text”, ”options” => array( ”label” => ”Author”, ), )); $this->add(array( ”name” => ”title”, ”type” => ”Text”, ”options” => array( ”label” => ”Title”, ), )); $this->add(array( ”name” => ”submit”, ”type” => ”Submit”, ”attributes” => array( ”value” => ”Go”, ”id” => ”submitbutton”, ), )); } } The Form class provides an add method to map the model and its corresponding form details. we have created the BookForm by extending the Form class and added the form details for Book model. Step 2: Update the book model, Book.php Update the model, ‘Book’ with filter and validation as specified below − <?php namespace TutorialModel; use ZendInputFilterInputFilterInterface; use ZendInputFilterInputFilterAwareInterface; use ZendInputFilterInputFilter; class Book implements InputFilterAwareInterface { public $id; public $author; public $title; protected $inputFilter; public function setInputFilter(InputFilterInterface $inputFilter) { throw new Exception(“Not used”); } public function getInputFilter() { if (!$this->inputFilter) { $inputFilter = new InputFilter(); $inputFilter->add(array( ”name” => ”id”, ”required” => true, ”filters” => array( array(”name” => ”Int”), ), )); $inputFilter->add(array( ”name” => ”author”, ”required” => true, ”filters” => array( array(”name” => ”StripTags”), array(”name” => ”StringTrim”), ), ”validators” => array( array( ”name” => ”StringLength”, ”options” => array( ”encoding” => ”UTF-8”, ”min” => 1, ”max” => 100, ), ), ), )); $inputFilter->add(array( ”name” => ”title”, ”required” => true, ”filters” => array( array(”name” => ”StripTags”), array(”name” => ”StringTrim”), ), ”validators” => array( array( ”name” => ”StringLength”, ”options” => array( ”encoding” => ”UTF-8”, ”min” => 1, ”max” => 100, ), ), ), )); $this->inputFilter = $inputFilter; } return $this->inputFilter; } 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; } } Each model should implement the InputFilterAwareInterface. The InputFilterAwareInterface provides two methods, setInputFilter() and getInputFilter(). The getInputFilter is used to get the validation details of the model. Zend framework provides a rich set of filters and validators to validate the form. Some of the filters and validators used in the book model are as follows − StripTags − Remove unwanted HTML. StringTrim − Remove unnecessary white space. StringLength validator − Ensure that the user does not enter more characters than the specified limit. Step 3: Update the BookTable class Include the saveBook method to add book to the database. BookTable.php <?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; } public function getBook($id) { $id = (int) $id; $rowset = $this->tableGateway->select(array(”id” => $id)); $row = $rowset->current(); if (!$row) { throw new Exception(“Could not find row $id”); } return $row; } public function saveBook(Book $book) { $data = array ( ”author” => $book->author, ”title” => $book->title, ); $id = (int) $book->id; if ($id == 0) { $this->tableGateway->insert($data); } else { if ($this->getBook($id)) { $this->tableGateway->update($data, array(”id” => $id)); } else { throw new Exception(”Book id does not exist”); } } } } Step 4: Update the TutorialController class Add a new action addAction in the tutorial controller – myapp/module/Tutorial/src/Controller/TutorialController.php. public function addAction() { $form = new BookForm(); $form->get(”submit”)->setValue(”Add”); $request = $this->getRequest(); if ($request->isPost()) { $book = new Book(); $form->setInputFilter($book->getInputFilter()); $form->setData($request->getPost()); if ($form->isValid()) { $book->exchangeArray($form->getData()); $this->bookTable->saveBook($book); // Redirect to list of Tutorial return $this->redirect()->toRoute(”tutorial”); } } return array(”form” => $form); } The addAction method does the following processes − Gets the request object. Checks if the request”s http method is a post method. If request”s http method is not post, it just renders the template, add.phtml If the request”s http method is not post, then it sets the inputfilter, gets the request data and sets it into the inputfiler. Checks whether the form is valid using the isValid() method of Form class. If the form is not valid, it again renders the template, add.phtml If the form is valid, it saves the book into the database and redirects to the home page. Step 5: Add the add.phtml template Create a template – add.phtml under myapp/module/Tutorial/view/tutorial/tutorial/add.phtml Add.phtml <?php $title = ”Add new Book”; $this->headTitle($title); ?> <h1><?php echo $this->escapeHtml($title); ?></h1> <?php if(!empty($form)) { $form->setAttribute(”action”, $this->url(”tutorial”, array(”action” => ”add”))); $form->prepare(); echo $this->form()->openTag($form); echo $this->formHidden($form->get(”id”)); echo $this->formRow($form->get(”author”)).”<br>”; echo $this->formRow($form->get(”title”)).”<br>”; echo $this->formSubmit($form->get(”submit”)); echo $this->form()->closeTag(); } Here, we are rendering the book form using the Form instance, $form. Step 6: Run the Application Now, we can run the application – http://localhost:8080/tutorial/add. Form Page Validate Error Page Print Page Previous Next Advertisements ”;
Zend Framework – Unit Testing ”; Previous Next In general, we can debug a PHP application by using the advanced debugger tool or by using simple commands like echo and die. In a web scenario, we need to test the business logics as well as the presentation layer. Forms in a web application can be tested by entering relevant test data to ensure that the forms are working as expected. The design of a website can be tested manually by using a browser. These type of test processes can be automated using unit testing. A unit test is essential in large projects. These unit tests will help to automate the testing process and alert the developer when something goes wrong. Setting up the PHPUnit Zend framework integrates with the PHPUnit unit testing framework. To write a unit test for the Zend framework, we need to setup the PHPUnit, which can be easily done by using the following Composer command. $ composer require –dev phpunit/phpunit After executing the above command, you will get a response as shown in the following code block. Using version ^5.7 for phpunit/phpunit ./composer.json has been updated Loading composer repositories with package information Updating dependencies (including require-dev) Nothing to install or update Writing lock file Generating autoload files Now, when you open the “composer.json” file, you will see the following changes − “require-dev”: { “phpunit/phpunit”: “^5.7″ } TestCase and Assertions The Zend framework provides helper classes to unit test the controller. The TestCase is the main component in a PHPUnit framework to write the test cases and the Zend Framework provides an abstract implementation of the TestCase that is called as the AbstractHttpControllerTestCase. This AbstractHttpControllerTestCase provides various Assert methods and can grouped by functionality. They are as follows − Request Assertions − Used to assert the http request. For example, assertControllerName. CSS Select Assertions − Used to check the response HTML using the HTML DOM model. XPath Assertions − An alternative to the CSS select assertions based on the XPath. Redirect Assertions − Used to check the page redirection. Response Header Assertions − Used to check the response header like status code (assertResponseStatusCode) Create Tests Directory A unit test can be written separately for each module. All test related coding need to be created inside the test folder under the module”s root directory. For example, to write a test for the TutorialController available under the Tutorial module, the test class needs to be placed under myapp/module/Tutorial/test/Controller/ directory. Example Let us write a test class to unit test the TutorialController. To begin with, we should write a class called TutorialControllerTest and extend it to the AbstractHttpControllerTestCase. The next step is to write a Setup method to setup the test environment. This can be done by calling the setApplicationConfig method and passing our main application config file myapp/config/application.config.php public function setUp() { $configOverrides = []; $this->setApplicationConfig(ArrayUtils::merge( include __DIR__ . ”/../../../../config/application.config.php”, $configOverrides )); parent::setUp(); } Write one or more methods and call various assert methods depending on the requirement. $this->assertMatchedRouteName(”tutorial”); We have written the test class and the complete listing is as follows − <?php namespace TutorialTestController; use TutorialControllerTutorialController; use ZendStdlibArrayUtils; use ZendTestPHPUnitControllerAbstractHttpControllerTestCase; class TutorialControllerTest extends AbstractHttpControllerTestCase { public function setUp() { $configOverrides = []; $this->setApplicationConfig(ArrayUtils::merge( include __DIR__ . ”/../../../../config/application.config.php”, $configOverrides )); parent::setUp(); } public function testIndexActionCanBeAccessed() { $this->dispatch(”/tutorial”, ”GET”); $this->assertResponseStatusCode(200); $this->assertModuleName(”tutorial”); $this->assertControllerName(TutorialController::class); $this->assertControllerClass(”TutorialController”); $this->assertMatchedRouteName(”tutorial”); } } Now, open a command prompt, move on to application root directory and execute the phpunit executable available inside the vendor folder. cd /path/to/app ./vendor/bin/phpunit ./vendor/bin/phpunit module/ Tutorial/test/Controller/TutorialControllerTest.php The result will be as shown in the following code block − PHPUnit 5.7.5 by Sebastian Bergmann and contributors. .1 / 1 (100%) Time: 96 ms, Memory: 8.00MB OK (1 test, 5 assertions) Print Page Previous Next Advertisements ”;
Zend Framework – Controllers
Zend Framework – Controllers ”; Previous Next As discussed earlier, the controller plays an important role in the Zend MVC Framework. All the webpages in an application needs to be handled by a controller. In the Zend MVC Framework, controllers are objects implementing the – Zend/Stdlib/DispatchableInterface. The DispatchableInterface has a single method, dispatch, which gets the Request object as input, do some logic and returns Response an object as the output. dispatch(Request $request, Response $response = null) A simple example of a Controller object to return “Hello World” is as follows − use ZendStdlibDispatchableInterface; use ZendStdlibRequestInterface as Request; use ZendStdlibResponseInterface as Response; class HelloWorld implements DispatchableInterface { public function dispatch(Request $request, Response $response = null) { $response->setContent(“Hello World!”); } } The DispatchableInterface is basic and it needs lot of other interfaces to write high level controllers. Some of such interfaces are as follows − InjectApplicationEventInterface − Used to inject events (Zend EventManager) ServiceLocatorAwareInterface − Used to locate Services (Zend ServiceManager) EventManagerAwareInterface − Used to manage events (Zend EventManager) Keeping these things in mind, the Zend Framework provides lot of readymade controllers implementing these interfaces. The most important controllers are as explained below. AbstractActionController The AbstractActionController (Zend/Mvc/Controller/AbstractActionController) is the most used controller in the Zend MVC Framework. It has all the necessary features to write a typical web page. It allows routes (Routing is matching request url to a controller and one of its methods) to match an action. When matched, a method named after the action will be called by the controller. For example, if a route test is matched and the route, test returns hello for action, then the helloAction method will be invoked. Let us write our TutorialController using the AbstractActionController. Create a new PHP class called TutorialController by extending the AbstractActionController and place it in the module/Tutorial/src/Controller/ directory. Set the TutorialController as the namespace. Write an indexAction method. Return the ViewModel object from indexAction method. The ViewModel object is used to send data from the controller to view engine, which we will see in the subsequent chapters. The complete code listing is as follows − ?php namespace TutorialController; use ZendMvcControllerAbstractActionController; use ZendViewModelViewModel; class TutorialController extends AbstractActionController { public function indexAction() { return new ViewModel(); } } We have successfully added the new TutorialController. AbstractRestfulController The AbstractRestfulController (ZendMvcControllerAbstractRestfulController) inspects the HTTP method of the incoming request and matches the action (method) by considering the HTTP methods For example, the request with GET HTTP method either matches the getList() method or the get() method, if the id parameter is found in the request. AbstractConsoleController The AbstractConsoleController (ZendMvcControllerAbstractConsoleController) is like the AbstractActionController except that it only runs in the console environment instead of a browser. Print Page Previous Next Advertisements ”;
Zend Framework – Routing
Zend Framework – Routing ”; Previous Next Routing maps Request URI to a specific controller”s method. In this chapter, we will see how to implement the routes in a Zend Framework. In general, any URI has three parts − Hostname segment, Path segment, and Query segment. For example, in URI / URL − http://www.example.com/index?q=data, www.example.com is the Hostname Segment, index is the Path Segment and q=data is the Query Segment. Generally, routing checks the Page segment against a set of constrain. If any constrain matches, then it returns a set of values. One of the main value is the controller. Routing also checks the host segment, query segment, request HTTP methods, request HTTP headers, etc., in a certain situation. Route & RouteStack Route is the main object in routing. Zend Framework has a special interface for route object, RouteInterface. All route object needs to implement RouteInterface. The complete listing of the RouteInterface is as follows − namespace ZendMvcRouter; use ZendStdlibRequestInterface as Request; interface RouteInterface { public static function factory(array $options = []); public function match(Request $request); public function assemble(array $params = [], array $options = []); } The main method is match. This match method checks the given request against the constrain defined in it. If any match is found, it returns the RouteMatch object. This RouteMatch object provides the details of the matched request as parameters. These parameters can be extracted from RouteObject using the getParams method. The complete listing of the RouteObject is as follows − namespace ZendMvcRouter; class RouteMatch { public function __construct(array $params); public function setMatchedRouteName($name); public function getMatchedRouteName(); public function setParam($name, $value); public function getParams(); public function getParam($name, $default = null); } In general, a typical MVC application has many routes. Each of this route will be processed in LIFO order and a single route will be matched and returned. If no route is matched / returned, then the application returns “Page not found” error. Zend Framework provides an interface to process the routes, RouteStackInterface. This RouteStackInterface has the option to add / remove routes. The complete listing of the RouteStackInterface is as follows − namespace ZendMvcRouter; interface RouteStackInterface extends RouteInterface { public function addRoute($name, $route, $priority = null); public function addRoutes(array $routes); public function removeRoute($name); public function setRoutes(array $routes); } Zend framework provides two implementations of the RouteStack interface and they are as follows − SimpleRouteStack TreeRouteStack Type of Routes Zend framework provides a lot of readymade route objects for all the situations under “ZendMvcRouterHttp” namespace. It is enough to select and use proper route object for the given situation. The available routes are as follows − Hostname − Used to match host part of the URI. Literal − Used to match exact URI. Method − Used to match HTTP method of the incoming request. Part − Used to match the part of the URI path segment using custom logic. Regex − Used to match the URI path segment by Regex Pattern. Schema − Used to match the URI Schema such as http, https, etc. Segment − Used to match URI path by splitting it into multiple segment. Let us see how to write the most commonly used literal and segment Route. Routes are usually specified in each module”s configuration file – module.config.php. Literal Route Typically, routes are queried in a LIFO order. The Literal route is for doing the exact matching of the URI path. It is defined as shown below − $route = Literal::factory(array( ”route” => ”/path”, ”defaults” => array(”controller” => ”ApplicationControllerIndexController”, ”action” => ”index”,), )); The above route matches the /path in the request url and returns index as the action and IndexController as controller. Segment Route A segmented route is used for whenever your url is supposed to contain variable parameters. It is described as given below − $route = Segment::factory(array( ”route” => ”/:controller[/:action]”, ”constraints” => array( ”controller” => ”[a-zA-Z][a-zA-Z0-9_-]+”, ”action” => ”[a-zA-Z][a-zA-Z0-9_-]+”, ), ”defaults” => array( ”controller” => ”ApplicationControllerIndexController”, ”action” => ”index”,), )); Here, Segments are denoted by a colon and followed by alphanumeric characters. If you keep a segment is optional then it is enclosed by brackets. Each segment may have constraints associated with it. Each constraint is a regular expression. Configuring Route in Tutorial Module Let us add a segment route in our Tutorial module. Update the tutorial module configuration file – module.config.php available at myapp/module/Tutorial/config. <?php namespace Tutorial; use ZendServiceManagerFactoryInvokableFactory; use ZendRouterHttpSegment; return [ ”controllers” => [ ”factories” => [ ControllerTutorialController::class => InvokableFactory::class, ], ], ”router” => [ ”routes” => [ ”tutorial” => [ ”type” => Segment::class, ”options” => [ ”route” => ”/tutorial[/:action[/:id]]”, ”constraints” => [ ”action” => ”[a-zA-Z][a-zA-Z0-9_-]*”, ”id” => ”[0-9]+”, ], ”defaults” => [ ”controller” => ControllerTutorialController::class, ”action” => ”index”, ], ], ], ], ], ”view_manager” => [ ”template_path_stack” => [”tutorial” => __DIR__ . ”/../view”,], ], ]; We have successfully added the routing for our Tutorial module. We are just one step behind in completing our Tutorial module. We need to add View for our module, which we will learn in the subsequent chapter. Print Page Previous Next Advertisements ”;
Zend Framework – Layout
Zend Framework – Layout ”; Previous Next A Layout represents the common parts of multiple views i.e. for example, page header and footer. By default, layouts should be stored in the view/layout folder. A Layout configuration is defined under the view_manager section in the module.config.php. The default configuration of the skeleton application is as follows − ”view_manager” => array( ”display_not_found_reason” => true, ”display_exceptions” => true, ”doctype” => ”HTML5”, ”not_found_template” => ”error/404”, ”exception_template” => ”error/index”, ”template_map” => array( ”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” => array( __DIR__ . ”/../view”, ), Here, the template_map is used to specify the layout. If layout is not found, then it will return an error. Let us have a look at the main layout of the skeleton application. Layout.phtml <?= $this->doctype() ?> <html lang = “en”> <head> <meta charset = “utf-8″> <?= $this->headTitle(”ZF Skeleton Application”)->setSeparator(” – ”)> setAutoEscape(false) ?> <?= $this->headMeta() ->appendName(”viewport”, ”width = device-width, initial-scale = 1.0”) ->appendHttpEquiv(”X-UA-Compatible”, ”IE = edge”) ?> <!– Le styles –> <?= $this->headLink([”rel” => ”shortcut icon”, ”type” => ”image/vnd.microsoft.icon”, ”href” => $this->basePath() . ”/img/favicon.ico”]) ->prependStylesheet($this->basePath(”css/style.css”)) ->prependStylesheet($this->basePath(”css/bootstraptheme.min.css”)) ->prependStylesheet($this->basePath(”css/bootstrap.min.css”)) ?> <!– Scripts –> <?= $this->headScript() ->prependFile($this->basePath(”js/bootstrap.min.js”)) ->prependFile($this->basePath(”js/jquery-3.1.0.min.js”)) ?> </head> <body> <nav class = “navbar navbar-inverse navbar-fixed-top” role = “navigation”> <div class = “container”> <div class = “navbar-header”> <button type = “button” class = “navbar-toggle” data- toggle = “collapse” data-target = “.navbar-collapse”> <span class = “icon-bar”></span> <span class = “icon-bar”></span> <span class = “icon-bar”></span> </button> <a class = “navbar-brand” href = “<?= $this->url(”home”) ?>”> <img src = “<?= $this->basePath(”img/zf-logo-mark.svg”) ?> ” height = “28” alt = “Zend Framework <?= ApplicationModule:: VERSION ?>”/> Skeleton Application </a> </div> <div class = “collapse navbar-collapse”> <ul class = “nav navbar-nav”> <li class = “active”><a href = “<?= $this->url(”home”) ?>”>Home</a></li> </ul> </div> </div> </nav> <div class = “container”> <?= $this->content ?> <hr> <footer> <p>© 2005 – <?= date(”Y”) ?> by Zend Technologies Ltd. All rights reserved.</p> </footer> </div> <?= $this->inlineScript() ?> </body> </html> As you analyze the layout, it mostly uses the view helpers, which we discussed in the previous chapter. As we look closer, the layout uses a special variable, $this->content. This variable is important as it will be replaced by the view script (template) of the actual requested page. Creating a new layout Let us create a new layout for our Tutorial module. To begin with, let us create a tutorial.css file under the “public/css” directory. body { background-color: lightblue; } h1 { color: white; text-align: center; } Create a new layout file newlayout.phtml at the /myapp/module/Tutorial/view/layout/ and copy the content from existing layout. Then, Add the tutorial.css stylesheet using the HeadLink helper class inside the layout head section. <?php echo $this->headLink()->appendStylesheet(”/css/tutorial.css”);?> Add a new about link in the navigation section using the URL helper. <li><a href = “<?= $this->url(”tutorial”, [”action” => ”about”]) ?>”>About</a></li> This layout page is common for the tutorial module application. Update the view_manager section of the tutorial module configuration file. ”view_manager” => array( ”template_map” => array( ”layout/layout” => __DIR__ . ”/../view/layout/newlayout.phtml”), ”template_path_stack” => array(”tutorial” => __DIR__ . ”/../view”,), ) Add the aboutAction function in the TutorialController. public function aboutAction() { } Add the about.phtml at myapp/module/Tutorial/view/tutorial/tutorial/ with the following content. <h2>About page</h2> Now, you are ready to finally run the application − http://localhost:8080/tutorial/about. Print Page Previous Next Advertisements ”;
Zend Framework – Useful Resources ”; Previous Next The following resources contain additional information on Zend Framework. Please use them to get more in-depth knowledge on this. Useful Video Courses .NET Framework Online Training Featured 8 Lectures 1 hours Tutorialspoint More Detail Learn Entity Framework Core 2.0 (EFC2) using ASP.Net Core 34 Lectures 3.5 hours Nilay Mehta More Detail Using Microsoft Bot Framework v3, LUIS, Cognitive Services 54 Lectures 4.5 hours Nilay Mehta More Detail Entity Framework : A Comprehensive Course 22 Lectures 2.5 hours TELCOMA Global More Detail Protractor Angular framework from scratch using java & nodeJS 19 Lectures 3 hours Lucky Trainings More Detail Java Spring Framework 5 – Build A Web App Step By Step Best Seller 122 Lectures 11 hours Damian Jedrzejak More Detail Print Page Previous Next Advertisements ”;
Zend Framework – Working Example ”; Previous Next In this chapter, we will learn how to create a complete MVC based Employee Application in Zend Framework. Follow the steps given below. Step 1: Module.php First, we should create an Employee module inside the – myapp/module/Employee/src/ directory and then implement the ConfigProviderInterface interface. The complete code for the Module class is as follows − <?php namespace Employee; use ZendModuleManagerFeatureConfigProviderInterface; class Module implements ConfigProviderInterface { public function getConfig() { return include __DIR__ . ”/../config/module.config.php”; } } Step 2: composer.json Configure the Tutorial module in composer.json under the autoload section by using the following code. “autoload”: { “psr-4”: { “Application\”: “module/Application/src/”, “Tutorial\”: “module/Tutorial/src/”, “Employee\”: “module/Employee/src/” } } Now, update the application using a composer update command. composer update The Composer command will do the necessary changes to the application and show the logs as shown in the command prompt 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 Step 3: module.config.php for the Employee Module Create the module configuration file, “module.config.php” under the myapp/module/Employee/config with the following code. <?php namespace Employee; use ZendServiceManagerFactoryInvokableFactory; use ZendRouterHttpSegment; return [ ”controllers” => [ ”factories” => [ ControllerEmployeeController::class => InvokableFactory::class, ], ], ”view_manager” => [ ”template_path_stack” => [”employee” => __DIR__ . ”/../view”,], ], ]; Now, configure the Employee module in the application level configuration file – myapp/config/modules.config.php. return [”ZendRouter”, ”ZendValidator”, ”Application”, ”Tutorial”, ”Employee”]; Step 4: EmployeeController Create a new PHP class, EmployeeController by extending the AbstractActionController and place it at the myapp/module/Employee/src/Controller directory. The complete code listing is as follows − <?php namespace EmployeeController; use ZendMvcControllerAbstractActionController; use ZendViewModelViewModel; class EmployeeController extends AbstractActionController { public function indexAction() { return new ViewModel(); } } Step 5: Router Configuration Let us add a segment route in our Employee module. Update the employee module configuration file, module.config.php available at myapp/module/Employee/config. <?php namespace Employee; use ZendServiceManagerFactoryInvokableFactory; use ZendRouterHttpSegment; return [ ”controllers” => [ ”factories” => [ ControllerEmployeeController::class => InvokableFactory::class, ], ], ”router” => [ ”routes” => [ ”employee” => [ ”type” => Segment::class, ”options” => [ ”route” => ”/employee[/:action[/:id]]”, ”constraints” => [ ”action” => ”[a-zA-Z][a-zA-Z0-9_-]*”, ”id” => ”[0-9]+”, ], ”defaults” => [ ”controller” => ControllerEmployeeController::class, ”action” => ”index”, ], ], ], ], ], ”view_manager” => [ ”template_path_stack” => [ ”employee” => __DIR__ . ”/../view”, ], ], ]; We have successfully added the routing for our Employee module. The next step is to create a view script for the Employee application. Step 6: Create ViewModel Create a file called as “index.phtml” under the myapp/module/Employee/view/employee/employee directory. Add the following changes in the file − <div class = “row content”> <h3>This is my first Zend application</h3> </div> Move to “EmployeeController.php” file and edit the following changes, <?php namespace EmployeeController; use ZendMvcControllerAbstractActionController; use ZendViewModelViewModel; class EmployeeController extends AbstractActionController { public function indexAction() { return new ViewModel(); } } Finally, we have successfully completed the Employee module. we can access it using the following url − http://localhost:8080/employee. Result In the next step, we will perform add, edit and delete data operations in the employee application. To perform these operations, we should first create a database model. It is described in the next step. Step 7: Create a Model Let us create a model, Employee in our module src directory. Generally, models are grouped under the Model folder (myapp/module/Employee/src/Model/Employee.php) <?php namespace EmployeeModel; class Employee { public $id; public $emp_name; public $emp_job; } Step 8: MySQL Table Create a database named as tutorials in the local MYSQL server using the following command − create database tutorials; Let us create a table named as employee in the database using following SQL command − use tutorials; CREATE TABLE employee ( id int(11) NOT NULL auto_increment, emp_name varchar(100) NOT NULL, emp_job varchar(100) NOT NULL, PRIMARY KEY (id) ); Insert data into the employee table using the following query − INSERT INTO employee (emp_name, emp_job) VALUES (”Adam”, ”Tutor”); INSERT INTO employee (emp_name, emp_job) VALUES (”Bruce”, ”Programmer”); INSERT INTO employee (emp_name, emp_job) VALUES (”David”, ”Designer”); Step 9: Update the Database Configuration Update the Global Configuration file, myapp/config/autoload/global.php with the necessary database drive information. return [ ”db” => [ ”driver” => ”Pdo”, ”dsn” => ”mysql:dbname = tutorials;host=localhost”, ”driver_options” => [PDO::MYSQL_ATTR_INIT_COMMAND => ”SET NAMES ”UTF8””], ], ]; Now, Update the database credentials in the local configuration file – myapp/config/autoload/local.php. In this way, we can separate local and live database connection credentials. <?php return array( ”db” => array(”username” => ”<user_name>”, ”password” => ”<password>”,), ); Step 10: Implement exchangeArray Implement exchangeArray function in Employee model. <?php namespace EmployeeModel; class Employee { public $id; public $emp_name; public $emp_job; public function exchangeArray($data) { $this->id = (!empty($data[”id”])) ? $data[”id”] : null; $this->emp_name = (!empty($data[”emp_name”])) ? $data[”emp_name”] : null; $this->emp_job = (!empty($data[”emp_job”])) ? $data[”emp_job”] : null; } } Step 11: Use TableGateway to fetch the Employee Data Create the class, EmployeeTable in the Model folder itself. It is defined in the following code block. <?php namespace EmployeeModel; use ZendDbTableGatewayTableGatewayInterface; class EmployeeTable { protected $tableGateway; public function __construct(TableGatewayInterface $tableGateway) { $this->tableGateway = $tableGateway; } public function fetchAll() { $resultSet = $this->tableGateway->select(); return $resultSet; } } Step 12: Configure EmployeeTable Class Update employee service in Module.php using getServiceConfig() method <?php namespace Employee; 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” => [ ModelEmployeeTable::class => function ( $container) { $tableGateway = $container>get( ModelEmployeeTableGateway::class); $table = new ModelEmployeeTable($tableGateway);
Application Structure
Zend Framework – Application Structure ”; Previous Next In this chapter, let us understand the structure of the Zend Framework application. The structure of the myapp application is as follows − ├── composer.json ├── composer.lock ├── CONDUCT.md ├── config │ ├── application.config.php │ ├── autoload │ │ ├── development.local.php │ │ ├── development.local.php.dist │ │ ├── global.php │ │ ├── local.php.dist │ │ ├── README.md │ │ └── zend-developer-tools.local-development.php │ ├── development.config.php │ ├── development.config.php.dist │ └── modules.config.php ├── CONTRIBUTING.md ├── data │ └── cache │ └── module-classmap-cache.application.module.cache.php ├── docker-compose.yml ├── Dockerfile ├── LICENSE.md ├── module │ └── Application │ ├── config │ ├── src │ ├── test │ └── view ├── phpcs.xml ├── phpunit.xml.dist ├── public │ ├── css │ │ ├── bootstrap.css │ │ ├── bootstrap.css.map │ │ ├── bootstrap.min.css │ │ ├── bootstrap.min.css.map │ │ ├── bootstrap-theme.css │ │ ├── bootstrap-theme.css.map │ │ ├── bootstrap-theme.min.css │ │ ├── bootstrap-theme.min.css.map │ │ └── style.css │ ├── fonts │ │ ├── glyphicons-halflings-regular.eot │ │ ├── glyphicons-halflings-regular.svg │ │ ├── glyphicons-halflings-regular.ttf │ │ ├── glyphicons-halflings-regular.woff │ │ └── glyphicons-halflings-regular.woff2 │ ├── img │ │ ├── favicon.ico │ │ └── zf-logo-mark.svg │ ├── index.php │ ├── js │ │ ├── bootstrap.js │ │ ├── bootstrap.min.js │ │ └── jquery-3.1.0.min.js │ └── web.config ├── README.md ├── TODO.md ├── Vagrantfile └── vendor ├── autoload.php ├── bin │ ├── phpunit -> ../phpunit/phpunit/phpunit │ ├── templatemap_generator.php -> ../zendframework/zend- view/bin/templatemap_generator.php │ └── zf-development-mode -> ../zfcampus/zf-development-mode/bin/zf- development-mode ├── composer │ ├── autoload_classmap.php │ ├── autoload_namespaces.php │ ├── autoload_psr4.php │ ├── autoload_real.php │ ├── ClassLoader.php │ ├── installed.json │ └── LICENSE ├── container-interop │ └── container-interop ├── doctrine │ └── instantiator ├── myclabs │ └── deep-copy ├── phpdocumentor │ ├── reflection-common │ ├── reflection-docblock │ └── type-resolver ├── phpspec │ └── prophecy ├── phpunit │ ├── php-code-coverage │ ├── php-file-iterator │ ├── php-text-template │ ├── php-timer │ ├── php-token-stream │ ├── phpunit │ └── phpunit-mock-objects ├── sebastian │ ├── code-unit-reverse-lookup │ ├── comparator │ ├── diff │ ├── environment │ ├── exporter │ ├── global-state │ ├── object-enumerator │ ├── recursion-context │ ├── resource-operations │ └── version ├── symfony │ └── yaml ├── webmozart │ └── assert ├── zendframework │ ├── zend-component-installer │ ├── zend-config │ ├── zend-console │ ├── zend-dom │ ├── zend-escaper │ ├── zend-eventmanager │ ├── zend-http │ ├── zend-loader │ ├── zend-modulemanager │ ├── zend-mvc │ ├── zend-router │ ├── zend-servicemanager │ ├── zend-stdlib │ ├── zend-test │ ├── zend-uri │ ├── zend-validator │ └── zend-view └── zfcampus └── zf-development-mode 73 directories, 55 files The Zend Framework application consists of different folders. They are as follows − Application − This directory contains your application. It will house the MVC system, as well as configurations, services used and your bootstrap file. Config − This directory contains the configuration files of an application. Data − This directory provides a place to store application data that is volatile and possibly temporary. Module − Modules allow a developer to group a set of related controllers into a logically organized group. Public − This is the application’s document root. It starts the Zend application. It also contains the assets of the application like JavaScript, CSS, Images, etc. Vendor − This directory contains composer dependencies. Structure of the Application Modules This is the main directory of your application. Zend Framework 2 introduces a powerful and flexible module system to organize the application efficiently. The Application module of the skeleton application (myapp) provides bootstrapping, error and routing configuration to the whole application. The structure of the Application module is as shown below − ├── module │ └── Application │ ├── config │ │ └── module.config.php │ ├── src │ │ ├── Controller │ │ │ └── IndexController.php │ │ └── Module.php │ ├── test │ │ └── Controller │ │ └── IndexControllerTest.php │ └── view │ ├── application │ │ └── index │ │ └── index.phtml │ ├── error │ │ ├── 404.phtml │ │ └── index.phtml │ └── layout │ └── layout.phtml Let us cover each of these module directories in detail − Application − This is root directory of the module. The name of the folder will match the name of the module and the name is also used as the PHP namespace of all the class defined inside the module. It will house the MVC system, as well as configurations, services used, and your bootstrap file. Config − Independent configuration of the module. Src − Main business logic of the application. View − Contains design / presentation (HTML) files. For example, index.phtml. src/Module.php − It is the heart of the module. It works as a “front controller” for the module. The Zend process src/Module.php file before processing any PHP Classes in this module. Application/config/module.config.php − It is implemented for the router configuration and auto loading files. Application/view/layout − Layouts represent the common parts of multiple views. For example, page header and footer. By default, layouts should be stored in the views/layoutsfolder. All modules share the same or similar structure as that of the above Application module. Print Page Previous Next Advertisements ”;