Zend Framework - View Layer


Advertisements


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 (Zend\View\View) − 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 Tutorial\Controller;  
use Zend\Mvc\Controller\AbstractActionController; 
use Zend\View\Model\ViewModel;  
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.

Application Template

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, Zend\View\Helper\HelperInterface to write standard view helpers.

A HelperInterface has just two methods,

  • setView() − This method accepts a Zend\View\Renderer\RendererInterface instance/implementation.

  • getView() − It is used to retrieve that instance.

The complete code listing of HelperInterface is as follows −

namespace Zend\View\Helper;  
use Zend\View\Renderer\RendererInterface 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 helper is used to generate various html doctypes. It is concrete implementation of the Placeholder helper. The doctype can be set in a bootstrap file and config file.

The basic usage is shown below −

Application Bootstrap file

use Zend\View\Helper\Doctype;  
$doctypeHelper = new Doctype(); 
$doctypeHelper->doctype('XHTML5'); 

Module Configuration

// module/Application/config/module.config.php: 
return [ 
   /* ... */ 
   'view_manager' => [ 
      'doctype' => 'html5', 
      /* ... */ 
   ], 
]; 

Template

<?php echo $this->doctype() ?> 

HeadTitle

The HeadTitle helper is used to generate the html title element. It is the concrete implementation of Placeholder helper. Zend provides an option to set the title in the module configuration file and it can be set at any level like site, module, controller, action, etc. A partial code for the HeadTitle is as follows −

Module

headTitleHelper->append($action); 
$headTitleHelper->append($controller); 
$headTitleHelper->append($module); 
$headTitleHelper->append($siteName);

Template

<?= $this->headTitle() ?>

Result

action - controller - module - Zend Framework

HeadMeta

The HeadMeta helper is used to generate html meta tags. It is a concrete implementation of the Placeholder helper.

Template

<?php 
   $this->headMeta()->appendName('keywords', 'turorialspoint, zend framework, php');  
   echo $this->headMeta() 
?>

Result

<meta name = "keywords" content = "tutorialspoint, zend framework, php" />

HeadLink

The HeadLink helper is used to generate html links to include external resources. It is concrete implementation of the Placeholder helper.

Template

<?php 
   // setting links in a view script: 
   $this->headLink(['rel' => 'icon', 'href' => '/img/favicon.ico'], 'PREPEND') 
      ->appendStylesheet('/styles/site.css') 
      ->prependStylesheet('/styles/mystyle.css', 'screen', true, ['id' => 'mystyle']);  
   
   // rendering the links from the layout: 
   echo $this->headLink(); 
?>

Result

<link href = "/styles/mystyle.css" media = "screen" rel = "stylesheet" 
   type = "text/css" id = "mystyle"> 
<link href = "/img/favicon.ico" rel = "icon"> 
<link href = "/styles/site.css" media = "screen" rel = "stylesheet" type = "text/css">

HeadStyle

The HeadStyle helper is used to generate inline CSS styles. It is concrete implementation of the Placeholder helper.

Template

<?php $this->headStyle()->appendStyle($styles); ?>  
<?php echo $this->headStyle() ?>

HeadScript

The HeadScript is used to generate inline script or to include external scripts. It is concrete implementation of the Placeholder helper.

Template

<? $this->headScript()->appendFile(‘/js/sample.js’);?>  
<?php echo $this->headScript() ?>

InlineScript

The InlineScript is used to generate a script in both head and body section of the html template. It is derived from the HeadScript.

HTMLList

The HTMLList is used to generate ordered and unordered list. The definition of the HTMLList is as follows −

Definition

htmlList($items, $ordered, $attribs, $escape) 

Template

$items = [ 
   '2015', 
   ['March', 'November'], 
   '2016', 
];  
echo $this->htmlList($items);

Result

<ul> 
   <li>2015 
      <ul> 
         <li>March</li> 
         <li>November</li> 
      </ul> 
   </li> 
   <li>2016</li> 
</ul>

Cycle

A Cycle is used to generate alternatives in a loop environment. It has assign, next and prev function.

Controller

$view = new ViewModel(['message' => 'Hello, Tutorial', 'data' => array('One', 'Two')]);

Template

<?php $this->cycle()->assign(['#F0F0F0', '#FFF'], 'colors'); ?>

<table>
   <?php foreach ($this->data as $datum): ?>
   <tr style = "background-color: <?= $this->cycle()->setName('colors')>next() ?>">
      <td><?= $this->escapeHtml($datum) ?></td>
   </tr>
   <?php endforeach ?>
</table>

Result

<table> 
   <tr style = "background-color: #F0F0F0"> 
      <td>One</td> 
   </tr> 
   <tr style = "background-color: #FFF"> 
      <td>Two</td> 
   </tr> 
</table>

A few other important built-in helpers are as follows −

  • BasePath − The BasePath is used to generate path of the public folder of the application's root.

  • Partial − Partial is used to render a specific template in its own variable scope.

  • PartialLoop − PartialLoop is like Partial, but used in the looping environment.

  • Identity − Identity is used to retrieve the logged-in user's identity from the Authentication Service.

  • JSON − JSON is used in a restful environment, where the output is in JSON format. It emits proper HTTP header and disables the layout concept.

There are still lot of helpers available in Zend Framework such as the i18n helper, form helpers, pagination helpers, navigation helpers, etc.

Creating View Helpers

The Zend Framework provides a built-in AbstractHelper implementing HelperInterface to write view helpers.

The steps involved in writing a new helper are as follows −

  • Step 1 − Extend the class Zend\View\Helper\AbstractHelper.

  • Step 2 − Override the __invoke() function.

  • Step 3 − Set the configuration in the module.config.php file.

  • Step 4 − Use view helper in view scripts.

Let us now create a TestHelper

Create Helper folder at myapp/module/Tutorial/src/View directory. Write TestHelper inside Helper directory, TestHelper.php.

The complete listing is as follows −

<?php  
namespace Tutorial\View\Helper; 
use Zend\View\Helper\AbstractHelper; 
class TestHelper extends AbstractHelper { 
   public function __invoke() { 
      $output = "I am from test helper"; 
      return htmlspecialchars($output, ENT_QUOTES, 'UTF-8'); 
   } 
}

Set configuration in module.config.php.

'view_helpers' => [ 
   'aliases' => [ 
      'testHelper' => View\Helper\TestHelper::class, 
   ], 
   'factories' => [ 
      View\Helper\TestHelper::class => InvokableFactory::class, 
   ],
], 

Use the newly created TestHelper in the about view script.

<?= $this->testHelper() ?> 


Advertisements
E-Books Store