Posted on

Zend_View View Scripts

View Scripts

Once your controller has assigned variables and called render(), Zend_View then includes the requested view script and executes it “inside” the scope of the Zend_View instance. Therefore, in your view scripts, references to $this actually point to the Zend_View instance itself.

Variables assigned to the view from the controller are referred to as instance properties. For example, if the controller were to assign a variable ‘something’, you would refer to it as $this->something in the view script. (This allows you to keep track of which values were assigned to the script, and which are internal to the script itself.)

By way of reminder, here is the example view script from the Zend_View introduction.

  1. <?php if ($this->books): ?>
  2. <!– A table of some books. –>
  3. <table>
  4. <tr>
  5. <th>Author</th>
  6. <th>Title</th>
  7. </tr>
  8. <?php foreach ($this->books as $key => $val): ?>
  9. <tr>
  10. <td><?php echo $this->escape($val[‘author’]) ?></td>
  11. <td><?php echo $this->escape($val[‘title’]) ?></td>
  12. </tr>
  13. <?php endforeach; ?>
  14. </table>
  15. <?php else: ?>
  16. <p>There are no books to display.</p>
  17. <?php endif;?>

Escaping Output

One of the most important tasks to perform in a view script is to make sure that output is escaped properly; among other things, this helps to avoid cross-site scripting attacks. Unless you are using a function, method, or helper that does escaping on its own, you should always escape variables when you output them.

Zend_View comes with a method called escape() that does such escaping for you.

  1. // bad view-script practice:
  2. echo $this->variable;
  3. // good view-script practice:
  4. echo $this->escape($this->variable);

By default, the escape() method uses the PHP htmlspecialchars() function for escaping. However, depending on your environment, you may wish for escaping to occur in a different way. Use the setEscape() method at the controller level to tell Zend_View what escaping callback to use.

  1. // create a Zend_View instance
  2. $view = new Zend_View();
  3. // tell it to use htmlentities as the escaping callback
  4. $view->setEscape(‘htmlentities’);
  5. // or tell it to use a static class method as the callback
  6. $view->setEscape(array(‘SomeClass’, ‘methodName’));
  7. // or even an instance method
  8. $obj = new SomeClass();
  9. $view->setEscape(array($obj, ‘methodName’));
  10. // and then render your view
  11. echo $view->render(…);

The callback function or method should take the value to be escaped as its first parameter, and all other parameters should be optional.

Using Alternate Template Systems

Although PHP is itself a powerful template system, many developers feel it is too powerful or complex for their template designers and will want to use an alternate template engine. Zend_View provides two mechanisms for doing so, the first through view scripts, the second by implementing Zend_View_Interface.

Template Systems Using View Scripts

A view script may be used to instantiate and manipulate a separate template object, such as a PHPLIB-style template. The view script for that kind of activity might look something like this:

  1. include_once ‘template.inc’;
  2. $tpl = new Template();
  3. if ($this->books) {
  4. $tpl->setFile(array(
  5. “booklist” => “booklist.tpl”,
  6. “eachbook” => “eachbook.tpl”,
  7. ));
  8. foreach ($this->books as $key => $val) {
  9. $tpl->set_var(‘author’, $this->escape($val[‘author’]);
  10. $tpl->set_var(‘title’, $this->escape($val[‘title’]);
  11. $tpl->parse(“books”, “eachbook”, true);
  12. }
  13. $tpl->pparse(“output”, “booklist”);
  14. } else {
  15. $tpl->setFile(“nobooks”, “nobooks.tpl”)
  16. $tpl->pparse(“output”, “nobooks”);
  17. }

These would be the related template files:

  1. <!– booklist.tpl –>
  2. <table>
  3. <tr>
  4. <th>Author</th>
  5. <th>Title</th>
  6. </tr>
  7. {books}
  8. </table>
  9. <!– eachbook.tpl –>
  10. <tr>
  11. <td>{author}</td>
  12. <td>{title}</td>
  13. </tr>
  14. <!– nobooks.tpl –>
  15. <p>There are no books to display.</p>

Template Systems Using Zend_View_Interface

Some may find it easier to simply provide a Zend_View-compatible template engine. Zend_View_Interface defines the minimum interface needed for compatability:

  1. /**
  2. * Return the actual template engine object
  3. */
  4. public function getEngine();
  5. /**
  6. * Set the path to view scripts/templates
  7. */
  8. public function setScriptPath($path);
  9. /**
  10. * Set a base path to all view resources
  11. */
  12. public function setBasePath($path, $prefix = ‘Zend_View’);
  13. /**
  14. * Add an additional base path to view resources
  15. */
  16. public function addBasePath($path, $prefix = ‘Zend_View’);
  17. /**
  18. * Retrieve the current script paths
  19. */
  20. public function getScriptPaths();
  21. /**
  22. * Overloading methods for assigning template variables as object
  23. * properties
  24. */
  25. public function __set($key, $value);
  26. public function __isset($key);
  27. public function __unset($key);
  28. /**
  29. * Manual assignment of template variables, or ability to assign
  30. * multiple variables en masse.
  31. */
  32. public function assign($spec, $value = null);
  33. /**
  34. * Unset all assigned template variables
  35. */
  36. public function clearVars();
  37. /**
  38. * Render the template named $name
  39. */
  40. public function render($name);

Using this interface, it becomes relatively easy to wrap a third-party template engine as a Zend_View-compatible class. As an example, the following is one potential wrapper for Smarty:

  1. class Zend_View_Smarty implements Zend_View_Interface
  2. {
  3. /**
  4. * Smarty object
  5. * @var Smarty
  6. */
  7. protected $_smarty;
  8. /**
  9. * Constructor
  10. *
  11. * @param string $tmplPath
  12. * @param array $extraParams
  13. * @return void
  14. */
  15. public function __construct($tmplPath = null, $extraParams = array())
  16. {
  17. $this->_smarty = new Smarty;
  18. if (null !== $tmplPath) {
  19. $this->setScriptPath($tmplPath);
  20. }
  21. foreach ($extraParams as $key => $value) {
  22. $this->_smarty->$key = $value;
  23. }
  24. }
  25. /**
  26. * Return the template engine object
  27. *
  28. * @return Smarty
  29. */
  30. public function getEngine()
  31. {
  32. return $this->_smarty;
  33. }
  34. /**
  35. * Set the path to the templates
  36. *
  37. * @param string $path The directory to set as the path.
  38. * @return void
  39. */
  40. public function setScriptPath($path)
  41. {
  42. if (is_readable($path)) {
  43. $this->_smarty->template_dir = $path;
  44. return;
  45. }
  46. throw new Exception(‘Invalid path provided’);
  47. }
  48. /**
  49. * Retrieve the current template directory
  50. *
  51. * @return string
  52. */
  53. public function getScriptPaths()
  54. {
  55. return array($this->_smarty->template_dir);
  56. }
  57. /**
  58. * Alias for setScriptPath
  59. *
  60. * @param string $path
  61. * @param string $prefix Unused
  62. * @return void
  63. */
  64. public function setBasePath($path, $prefix = ‘Zend_View’)
  65. {
  66. return $this->setScriptPath($path);
  67. }
  68. /**
  69. * Alias for setScriptPath
  70. *
  71. * @param string $path
  72. * @param string $prefix Unused
  73. * @return void
  74. */
  75. public function addBasePath($path, $prefix = ‘Zend_View’)
  76. {
  77. return $this->setScriptPath($path);
  78. }
  79. /**
  80. * Assign a variable to the template
  81. *
  82. * @param string $key The variable name.
  83. * @param mixed $val The variable value.
  84. * @return void
  85. */
  86. public function __set($key, $val)
  87. {
  88. $this->_smarty->assign($key, $val);
  89. }
  90. /**
  91. * Allows testing with empty() and isset() to work
  92. *
  93. * @param string $key
  94. * @return boolean
  95. */
  96. public function __isset($key)
  97. {
  98. return (null !== $this->_smarty->get_template_vars($key));
  99. }
  100. /**
  101. * Allows unset() on object properties to work
  102. *
  103. * @param string $key
  104. * @return void
  105. */
  106. public function __unset($key)
  107. {
  108. $this->_smarty->clear_assign($key);
  109. }
  110. /**
  111. * Assign variables to the template
  112. *
  113. * Allows setting a specific key to the specified value, OR passing
  114. * an array of key => value pairs to set en masse.
  115. *
  116. * @see __set()
  117. * @param string|array $spec The assignment strategy to use (key or
  118. * array of key => value pairs)
  119. * @param mixed $value (Optional) If assigning a named variable,
  120. * use this as the value.
  121. * @return void
  122. */
  123. public function assign($spec, $value = null)
  124. {
  125. if (is_array($spec)) {
  126. $this->_smarty->assign($spec);
  127. return;
  128. }
  129. $this->_smarty->assign($spec, $value);
  130. }
  131. /**
  132. * Clear all assigned variables
  133. *
  134. * Clears all variables assigned to Zend_View either via
  135. * {@link assign()} or property overloading
  136. * ({@link __get()}/{@link __set()}).
  137. *
  138. * @return void
  139. */
  140. public function clearVars()
  141. {
  142. $this->_smarty->clear_all_assign();
  143. }
  144. /**
  145. * Processes a template and returns the output.
  146. *
  147. * @param string $name The template to process.
  148. * @return string The output.
  149. */
  150. public function render($name)
  151. {
  152. return $this->_smarty->fetch($name);
  153. }
  154. }

In this example, you would instantiate the Zend_View_Smarty class instead of Zend_View, and then use it in roughly the same fashion as Zend_View:

  1. //Example 1. In initView() of initializer.
  2. $view = new Zend_View_Smarty(‘/path/to/templates’);
  3. $viewRenderer =
  4. Zend_Controller_Action_HelperBroker::getStaticHelper(‘ViewRenderer’);
  5. $viewRenderer->setView($view)
  6. ->setViewBasePathSpec($view->_smarty->template_dir)
  7. ->setViewScriptPathSpec(‘:controller/:action.:suffix’)
  8. ->setViewScriptPathNoControllerSpec(‘:action.:suffix’)
  9. ->setViewSuffix(‘tpl’);
  10. //Example 2. Usage in action controller remains the same…
  11. class FooController extends Zend_Controller_Action
  12. {
  13. public function barAction()
  14. {
  15. $this->view->book   = ‘Zend PHP 5 Certification Study Guide’;
  16. $this->view->author = ‘Davey Shafik and Ben Ramsey’
  17. }
  18. }
  19. //Example 3. Initializing view in action controller
  20. class FooController extends Zend_Controller_Action
  21. {
  22. public function init()
  23. {
  24. $this->view   = new Zend_View_Smarty(‘/path/to/templates’);
  25. $viewRenderer = $this->_helper->getHelper(‘viewRenderer’);
  26. $viewRenderer->setView($this->view)
  27. ->setViewBasePathSpec($view->_smarty->template_dir)
  28. ->setViewScriptPathSpec(‘:controller/:action.:suffix’)
  29. ->setViewScriptPathNoControllerSpec(‘:action.:suffix’)
  30. ->setViewSuffix(‘tpl’);
  31. }