English 中文(简体)
Zend Framework - View Layer
  • 时间:2025-02-05

Zend Framework - View Layer


Previous Page Next Page  

A View Layer is the presentation layer of the MVC apppcation. It separates the apppcation logic from the presentation logic. In a typical PHP web apppcation, 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 apppcation, 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 accomppshed 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 psting is as follows −

<?php  
namespace TutorialController;  
use ZendMvcControllerAbstractActionController; 
use ZendViewModelViewModel;  
class TutorialController extends AbstractActionController { 
   pubpc function indexAction() { 
   } 
}

Zend Apppcation Template

<span class = "row content"> 
   <h3>This is my first Zend apppcation</h3> 
</span>

Finally, we have successfully completed the Tutorial module and we can access it using url – http://localhost:8080/tutorial.

Apppcation 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 −

pubpc function indexAction() { 
   $view = new ViewModel([ 
       message  =>  Hello, Tutorial  
   ]);  
   return $view; 
} 

Now, change the index.phtml file as follows −

<span class = "row content"> 
   <h3>This is my first Zend apppcation</h3> 
   <h4><?php echo $this->message?></h4> 
</span>

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 psting of HelperInterface is as follows −

namespace ZendViewHelper;  
use ZendViewRendererRendererInterface as Renderer;  
interface HelperInterface { 
   /** 
      * Set the View object 
      * 
      * @param  Renderer $view 
      * @return HelperInterface 
   */ 
   pubpc function setView(Renderer $view);  
   /** 
      * Get the View object 
      * 
      * @return Renderer 
   */ 
   pubpc 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 apppcation.

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 productpst placeholder.

Class – Product

class Product { 
   pubpc $name; 
   pubpc $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( productpst )->captureStart(); 
   foreach ($this->products as $product): ?> 
<span> 
   <h2><?= $product->name ?></h2> 
   <p><?= $product->description ?></p> 
</span> 
<?php endforeach; ?> 
<?php $this->placeholder( productpst )->captureEnd() ?> 
<!-- end capture -->  
<?= $this->placeholder( productpst ) ?> 

Result

<span class = "foo"> 
   <h2>Car</h2> 
   <p>Car</p> 
</span>
<span class = "foo"> 
   <h2>Cycle</h2> 
   <p>Cycle</p> 
</span> 

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 −

Apppcation Bootstrap file

use ZendViewHelperDoctype;  
$doctypeHelper = new Doctype(); 
$doctypeHelper->doctype( XHTML5 ); 

Module Configuration

// module/Apppcation/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 pke 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 pnks to include external resources. It is concrete implementation of the Placeholder helper.

Template

<?php 
   // setting pnks 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 pnks from the layout: 
   echo $this->headLink(); 
?>

Result

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

HeadStyle

The HeadStyle helper is used to generate inpne 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 inpne 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() ?>

InpneScript

The InpneScript 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 pst. 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> 
   <p>2015 
      <ul> 
         <p>March</p> 
         <p>November</p> 
      </ul> 
   </p> 
   <p>2016</p> 
</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 pubpc folder of the apppcation s root.

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

    PartialLoop − PartialLoop is pke 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 ZendViewHelperAbstractHelper.

    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 psting is as follows −

<?php  
namespace TutorialViewHelper; 
use ZendViewHelperAbstractHelper; 
class TestHelper extends AbstractHelper { 
   pubpc function __invoke() { 
      $output = "I am from test helper"; 
      return htmlspecialchars($output, ENT_QUOTES,  UTF-8 ); 
   } 
}

Set configuration in module.config.php.

 view_helpers  => [ 
    apases  => [ 
       testHelper  => ViewHelperTestHelper::class, 
   ], 
    factories  => [ 
      ViewHelperTestHelper::class => InvokableFactory::class, 
   ],
], 

Use the newly created TestHelper in the about view script.

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