View Scripts | Zend_View Programmer's Reference Guide | Zend_View_Abstract

# View Helpers

In your view scripts, often it is necessary to perform certain complex functions over and over: e.g., formatting a date, generating form elements, or displaying action links. You can use helper classes to perform these behaviors for you.

A helper is simply a class. Let's say we want a helper named 'fooBar'. By default, the class is prefixed with 'Zend_View_Helper_' (you can specify a custom prefix when setting a helper path), and the last segment of the class name is the helper name; this segment should be TitleCapped; the full class name is then: Zend_View_Helper_FooBar. This class should contain at the minimum a single method, named after the helper, and camelCased: fooBar().

> Note: Watch the Case
> Helper names are always camelCased, i.e., they never begin with an uppercase character. The class name itself is MixedCased, but the method that is actually executed is camelCased.

> Note: Default Helper Path
> The default helper path always points to the Zend Framework view helpers, i.e., 'Zend/View/Helper/'. Even if you call setHelperPath() to overwrite the existing paths, this path will be set to ensure the default helpers work.

To use a helper in your view script, call it using $this->helperName(). Behind the scenes, Zend_View will load the Zend_View_Helper_HelperName class, create an object instance of it, and call its helperName() method. The object instance is persistent within the Zend_View instance, and is reused for all future calls to $this->helperName().

# Initial Helpers

Zend_View comes with an initial set of helper classes, most of which relate to form element generation and perform the appropriate output escaping automatically. In addition, there are helpers for creating route-based URLs and HTML lists, as well as declaring variables. The currently shipped helpers include:

- declareVars(): Primarily for use when using strictVars(), this helper can be used to declare template variables that may or may not already be set in the view object, as well as to set default values. Arrays passed as arguments to the method will be used to set default values; otherwise, if the variable does not exist, it is set to an empty string.

- fieldset($name, $content, $attribs): Creates an XHTML fieldset. If $attribs contains a 'legend' key, that value will be used for the fieldset legend. The fieldset will surround the $content as provided to the helper.

- form($name, $attribs, $content): Generates an XHTML form. All $attribs are escaped and rendered as XHTML attributes of the form tag. If $content is present and not a boolean `FALSE`, then that content is rendered within the start and close form tags; if $content is a boolean `FALSE` (the default), only the opening form tag is generated.

- formButton($name, $value, $attribs): Creates an <button /> element.

- formCheckbox($name, $value, $attribs, $options): Creates an <input type="checkbox" /> element.

  By default, when no $value is provided and no $options are present, '0' is assumed to be the unchecked value, and '1' the checked value. If a $value is passed, but no $options are present, the checked value is assumed to be the value passed. The unchecked value is implemented by rendering a hidden input element before rendering the checkbox.

  $options should be an array. If the array is indexed, the first value is the checked value, and the second the unchecked value; all other values are ignored. You may also pass an associative array with the keys 'checked' and 'unChecked'. The key 'disableHidden' can be set to true to prevent rendering of the hidden field for the unchecked value.

  If $options has been passed, if $value matches the checked value, then the element will be marked as checked. You may also mark the element as checked or unchecked by passing a boolean value for the attribute 'checked'.

  The above is probably best summed up with some examples:

  1. // '1' and '0' as checked/unchecked options; not checked
  2. echo $this->formCheckbox('foo');
  4. // '1' and '0' as checked/unchecked options; checked
  5. echo $this->formCheckbox('foo', null, array ('checked' => true));
  7. // 'bar' and '0' as checked/unchecked options; not checked
  8. echo $this->formCheckbox('foo', 'bar');
  10. // 'bar' and '0' as checked/unchecked options; checked
  11. echo $this->formCheckbox('foo', 'bar', array ('checked' => true));
  13. // 'bar' and 'baz' as checked/unchecked options; unchecked
  14. echo $this->formCheckbox('foo', null, null, array ('bar', 'baz'));
  16. // 'bar' and 'baz' as checked/unchecked options; unchecked
  17. echo $this->formCheckbox('foo', null, null, array (
  18. 'checked' => 'bar',
  19. 'unChecked' => 'baz'
  20. ));
  22. // 'bar' and 'baz' as checked/unchecked options; checked
  23. echo $this->formCheckbox('foo', 'bar', null, array ('bar', 'baz'));
  24. echo $this->formCheckbox('foo',
  25. null,
  26. array ('checked' => true),
  27. array ('bar', 'baz'));
  29. // 'bar' and 'baz' as checked/unchecked options; unchecked
  30. echo $this->formCheckbox('foo', 'baz', null, array ('bar', 'baz'));
  31. echo $this->formCheckbox('foo',
  32. null,
  33. array ('checked' => false),
  34. array ('bar', 'baz'));

  In all cases, the markup prepends a hidden element with the unchecked value; this way, if the value is unchecked, you will still get a valid value returned to your form.

- formErrors($errors, $options): Generates an XHTML unordered list to show errors. $errors should be a string or an array of strings; $options should be any attributes you want placed in the opening list tag.

  You can specify alternate opening, closing, and separator content when rendering the errors by calling several methods on the helper:

  - setElementStart($string); default is '<ul class="errors"%s"><li>', where %s is replaced with the attributes as specified in $options.

  - setElementSeparator($string); default is '</li><li>'.

  - setElementEnd($string); default is '</li></ul>'.

- formFile($name, $attribs): Creates an <input type="file" /> element.

- formHidden($name, $value, $attribs): Creates an <input type="hidden" /> element.

- formImage($name, $value, $attribs): Creates an <input type="image" /> element.

  1. echo $this->formImage(
  2. 'foo',
  3. 'bar',
  4. array (
  5. 'src' => 'images/button.png',
  6. 'alt' => 'Button',
  7. )
  8. );
  9. // Output: <input type="image" name="foo" id="foo" src="images/button.png" value="bar" alt="Button" />

- formLabel($name, $value, $attribs): Creates a <label> element, setting the for attribute to $name, and the actual label text to $value. If disable is passed in attribs, nothing will be returned.

- formMultiCheckbox($name, $value, $attribs, $options, $listsep): Creates a list of checkboxes. $options should be an associative array, and may be arbitrarily deep. $value may be a single value or an array of selected values that match the keys in the $options array. $listsep is an HTML break ("<br />") by default. By default, this element is treated as an array; all checkboxes share the same name, and are submitted as an array.

  1. // Using list separator ($listsep):
  3. echo '<ul><li>';
  4. echo $view->formMultiCheckbox(
  5. 'foo',
  6. 2,
  7. array (
  8. 'class' => 'baz',
  9. ),
  10. array (
  11. 1 => 'One',
  12. 2 => 'Two',
  13. 3 => 'Three',
  14. ),
  15. "</li>\n<li>"
  16. );
  17. echo '</li></ul>';
  19. /*
  20. Output:
  21. <ul>
  22. <li>
  23. <label for="foo-1">
  24. <input type="checkbox" name="foo[]" id="foo-1" value="1" class="baz" />One
  25. </label>
  26. </li>
  27. <li>
  28. <label for="foo-2">
  29. <input type="checkbox" name="foo[]" id="foo-2" value="2" checked="checked" class="baz" />Two
  30. </label>
  31. </li>
  32. <li>
  33. <label for="foo-3">
  34. <input type="checkbox" name="foo[]" id="foo-3" value="3" class="baz" />Three</label>
  35. </li>
  36. </ul>
  37. */
  39. // Using options for label elements:
  40. echo $this->formMultiCheckbox(
  41. 'foo',
  42. 2,
  43. array (
  44. 'label_placement' => 'prepend',
  45. 'label_class' => 'baz',
  46. ),
  47. array (
  48. 1 => 'One',
  49. 2 => 'Two',
  50. 3 => 'Three',
  51. )
  52. );
  54. /*
  55. Output:
  56. <label class="baz" for="foo-1">
  57. One<input type="checkbox" name="foo[]" id="foo-1" value="1" />
  58. </label>
  59. <br />
  60. <label class="baz" for="foo-2">
  61. Two<input type="checkbox" name="foo[]" id="foo-2" value="2" checked="checked" />
  62. </label>
  63. <br />
  64. <label class="baz" for="foo-3">
  65. Three<input type="checkbox" name="foo[]" id="foo-3" value="3" />
  66. </label>
  67. */

- formNote($name, $value = null): Creates a simple text note. (e.g. as element for headlines in a Zend_Form object)

  1. echo $this->formNote(null, 'This is an example text.');
  2. // Output: This is an example text.

- formPassword($name, $value, $attribs): Creates an <input type="password" /> element.

- formRadio($name, $value, $attribs, $options, $listsep): Creates a series of <input type="radio" /> elements, one for each of the $options elements. In the $options array, the element key is the radio value, and the element value is the radio label. The $value radio will be preselected for you.

  1. // Using list separator ($listsep)
  3. echo '<ul><li>';
  4. echo $this->formRadio(
  5. 'foo',
  6. 2,
  7. array (
  8. 'class' => 'baz',
  9. ),
  10. array (
  11. 1 => 'One',
  12. 2 => 'Two',
  13. 3 => 'Three',
  14. ),
  15. "</li>\n<li>"
  16. );
  17. echo '</li></ul>';
  19. /*
  20. Output:
  21. <ul>
  22. <li>
  23. <label for="foo-1">
  24. <input type="radio" name="foo" id="foo-1" value="1" class="baz" />One
  25. </label>
  26. </li>
  27. <li>
  28. <label for="foo-2">
  29. <input type="radio" name="foo" id="foo-2" value="2" checked="checked" class="baz" />Two
  30. </label>
  31. </li>
  32. <li>
  33. <label for="foo-3">
  34. <input type="radio" name="foo" id="foo-3" value="3" class="baz" />Three
  35. </label>
  36. </li>
  37. </ul>
  38. */
  40. // Using options for label elements:
  42. echo $this->formRadio(
  43. 'foo',
  44. 2,
  45. array (
  46. 'label_placement' => 'prepend',
  47. 'label_class' => 'baz',
  48. ),
  49. array (
  50. 1 => 'One',
  51. 2 => 'Two',
  52. 3 => 'Three',
  53. )
  54. );
  56. /*
  57. Output:
  58. <label class="baz" for="foo-1">
  59. One<input type="radio" name="foo" id="foo-1" value="1" />
  60. </label>
  61. <br />
  62. <label class="baz" for="foo-2">
  63. Two<input type="radio" name="foo" id="foo-2" value="2" checked="checked" />
  64. </label>
  65. <br />
  66. <label class="baz" for="foo-3">
  67. Three<input type="radio" name="foo" id="foo-3" value="3" />
  68. </label>
  69. */

- formReset($name, $value, $attribs): Creates an <input type="reset" /> element.

- formSelect($name, $value, $attribs, $options): Creates a <select>...</select> block, with one <option>one for each of the $options elements. In the $options array, the element key is the option value, and the element value is the option label. The $value option(s) will be preselected for you.

  1. // Using option groups:
  3. echo $view->formSelect(
  4. 'foo',
  5. 2,
  6. array (
  7. 'class' => 'baz',
  8. ),
  9. array (
  10. 1 => 'One',
  11. 'Two' => array (
  12. '2.1' => 'One',
  13. '2.2' => 'Two',
  14. '2.3' => 'Three',
  15. ),
  16. 3 => 'Three',
  17. )
  18. );
  20. /*
  21. Output:
  22. <select name="foo" id="foo" class="baz">
  23. <option value="1" label="One">One</option>
  24. <optgroup id="foo-optgroup-Two" label="Two">
  25. <option value="2.1" label="One">One</option>
  26. <option value="2.2" label="Two">Two</option>
  27. <option value="2.3" label="Three">Three</option>
  28. </optgroup>
  29. <option value="3" label="Three">Three</option>
  30. </select>
  31. */
  33. // First example with 'multiple' option:
  35. echo $this->formSelect(
  36. 'foo[]',
  37. 2,
  38. null,
  39. array (
  40. 1 => 'One',
  41. 2 => 'Two',
  42. 3 => 'Three',
  43. )
  44. );
  46. /*
  47. Output:
  48. <select name="foo[]" id="foo" multiple="multiple">
  49. <option value="1" label="One">One</option>
  50. <option value="2" label="Two" selected="selected">Two</option>
  51. <option value="3" label="Three">Three</option>
  52. </select>
  53. */
  55. // Second example with 'multiple' option:
  57. echo $this->formSelect(
  58. 'foo',
  59. array (
  60. 1,
  61. 2,
  62. ),
  63. array (
  64. 'multiple' => true,
  65. ),
  66. array (
  67. 1 => 'One',
  68. 2 => 'Two',
  69. 3 => 'Three',
  70. )
  71. );
  73. /*
  74. Output:
  75. <select name="foo[]" id="foo" multiple="multiple">
  76. <option value="1" label="One" selected="selected">One</option>
  77. <option value="2" label="Two" selected="selected">Two</option>
  78. <option value="3" label="Three">Three</option>
  79. </select>
  80. */

- formSubmit($name, $value, $attribs): Creates an <input type="submit" /> element.

- formText($name, $value, $attribs): Creates an <input type="text" /> element.

- formTextarea($name, $value, $attribs): Creates a <textarea>...</textarea> block.

- url($urlOptions, $name, $reset, $encode): Creates a URL string based on a named route. $urlOptions should be an associative array of key/value pairs used by the particular route.

  1. // Using without options: (current request is: user/id/1)
  2. echo $this->url();
  3. // Output: user/info/id/1
  5. // Set URL options:
  6. echo $this->url(
  7. array ('controller' => 'user', 'action' => 'info', 'username' => 'foobar')
  8. );
  9. // Output: user/info/username/foobar
  11. // Using a route:
  12. $router->addRoute(
  13. 'user',
  14. new Zend_Controller_Router_Route(
  15. 'user/:username',
  16. array (
  17. 'controller' => 'user',
  18. 'action' => 'info',
  19. )
  20. )
  21. );
  23. echo $this->url( array ('name' => 'foobar'), 'user');
  24. // Output: user/foobar
  26. // Using reset: (current request is: user/id/1)
  27. echo $this->url( array ('controller' => 'user', 'action' => 'info'), null, false);
  28. // Output: user/info/id/1
  30. echo $this->url( array ('controller' => 'user', 'action' => 'info'), null, true);
  31. // Output: user/info
  33. // Using encode:
  34. echo $this->url(
  35. array ('controller' => 'user', 'action' => 'info', 'username' => 'John Doe'), null, true, false
  36. );
  37. // Output: user/info/username/John Doe
  39. echo $this->url(
  40. array ('controller' => 'user', 'action' => 'info', 'username' => 'John Doe'), null, true, false
  41. );
  42. // Output: user/info/username/John+Doe

- serverUrl($requestUri = null): Helper for returning the current server URL (optionally with request URI).

  1. // Current server URL in the example is: http://www.example.com/foo.html
  3. echo $this->serverUrl();
  4. // Output: http://www.example.com
  6. echo $this->serverUrl(true);
  7. // Output: http://www.example.com/foo.html
  9. echo $this->serverUrl('/foo/bar');
  10. // Output: http://www.example.com/foo/bar
  12. echo $this->serverUrl()->getHost();
  13. // Output: www.example.com
  15. echo $this->serverUrl()->getScheme();
  16. // Output: http
  18. $this->serverUrl()->setHost('www.foo.com');
  19. $this->serverUrl()->setScheme('https');
  20. echo $this->serverUrl();
  21. // Output: https://www.foo.com

- htmlList($items, $ordered, $attribs, $escape): generates unordered and ordered lists based on the $items passed to it. If $items is a multidimensional array, a nested list will be built. If the $escape flag is `TRUE` (default), individual items will be escaped using the view objects registered escaping mechanisms; pass a `FALSE` value if you want to allow markup in your lists.

Using these in your view scripts is very easy, here is an example. Note that you all you need to do is call them; they will load and instantiate themselves as they are needed.

1. // inside your view script, $this refers to the Zend_View instance.
2. //
3. // say that you have already assigned a series of select options under
4. // the name $countries as array('us' => 'United States', 'il' =>
5. // 'Israel', 'de' => 'Germany').
6. ?>
7. <form action="action.php" method="post">
8. <p><label>Your Email:
9. <?php echo $this->formText('email', 'you@example.com', array ('size' => 32)) ?>
10. </label></p>
11. <p><label>Your Country:
12. <?php echo $this->formSelect('country', 'us', null, $this->countries) ?>
13. </label></p>
14. <p><label>Would you like to opt in?
15. <?php echo $this->formCheckbox('opt_in', 'yes', null, array ('yes', 'no')) ?>
16. </label></p>
17. </form>

The resulting output from the view script will look something like this:

1. <form action="action.php" method="post">
2. <p><label>Your Email:
3. <input type="text" name="email" value="you@example.com" size="32" />
4. </label></p>
5. <p><label>Your Country:
6. <select name="country">
7. <option value="us" selected="selected">United States</option>
8. <option value="il">Israel</option>
9. <option value="de">Germany</option>
10. </select>
11. </label></p>
12. <p><label>Would you like to opt in?
13. <input type="hidden" name="opt_in" value="no" />
14. <input type="checkbox" name="opt_in" value="yes" checked="checked" />
15. </label></p>
16. </form>

# Action View Helper

The Action view helper enables view scripts to dispatch a given controller action; the result of the response object following the dispatch is then returned. These can be used when a particular action could generate re-usable content or "widget-ized" content.

Actions that result in a _forward() or redirect are considered invalid, and will return an empty string.

The API for the Action view helper follows that of most MVC components that invoke controller actions: action($action, $controller, $module = null, array $params = array()). $action and $controller are required; if no module is specified, the default module is assumed.

Example #1 Basic Usage of Action View Helper

As an example, you may have a CommentController with a listAction() method you wish to invoke in order to pull a list of comments for the current request:

1. <div id="sidebar right">
2. <div class="item">
3. <?php echo $this->action('list',
4. 'comment',
5. null,
6. array ('count' => 10)); ?>
7. </div>
8. </div>

# BaseUrl Helper

While most URLs generated by the framework have the base URL prepended automatically, developers will need to prepend the base URL to their own URLs in order for paths to resources to be correct.

Usage of the BaseUrl helper is very straightforward:

1. /*
2. * The following assume that the base URL of the page/application is "/mypage".
3. */
5. /*
6. * Prints:
7. * <base href="/mypage/" />
8. */
9. <base href="<?php echo $this->baseUrl(); ?>" />
11. /*
12. * Prints:
13. * <link rel="stylesheet" type="text/css" href="/mypage/css/base.css" />
14. */
15. <link rel="stylesheet" type="text/css"
16. href="<?php echo $this->baseUrl('css/base.css'); ?>" />

> Note: For simplicity's sake, we strip out the entry PHP file (e.g., "index.php") from the base URL that was contained in Zend_Controller. However, in some situations this may cause a problem. If one occurs, use $this->getHelper('BaseUrl')->setBaseUrl() to set your own BaseUrl.

# Currency Helper

Displaying localized currency values is a common task; the Zend_Currency view helper is intended to simply this task. See the Zend_Currency documentation for specifics on this localization feature. In this section, we will focus simply on usage of the view helper.

There are several ways to initiate the Currency view helper:

- Registered, through a previously registered instance in Zend_Registry.

- Afterwards, through the fluent interface.

- Directly, through instantiating the class.

A registered instance of Zend_Currency is the preferred usage for this helper. Doing so, you can select the currency to be used prior to adding the adapter to the registry.

There are several ways to select the desired currency. First, you may simply provide a currency string; alternately, you may specify a locale. The preferred way is to use a locale as this information is automatically detected and selected via the HTTP client headers provided when a user accesses your application, and ensures the currency provided will match their locale.

> Note: We are speaking of "locales" instead of "languages" because a language may vary based on the geographical region in which it is used. For example, English is spoken in different dialects: British English, American English, etc. As a currency always correlates to a country you must give a fully-qualified locale, which means providing both the language and region. Therefore, we say "locale" instead of "language."

Example #2 Registered instance

To use a registered instance, simply create an instance of Zend_Currency and register it within Zend_Registry using Zend_Currency as its key.

1. // our example currency
2. $currency = new Zend_Currency('de_AT');
3. Zend_Registry::set('Zend_Currency', $currency);
5. // within your view
6. echo $this->currency(1234.56);
7. // this returns '€ 1.234,56'

If you are more familiar with the fluent interface, then you can also create an instance within your view and configure the helper afterwards.

Example #3 Within the view

To use the fluent interface, create an instance of Zend_Currency, call the helper without a parameter, and call the setCurrency() method.

1. // within your view
2. $currency = new Zend_Currency('de_AT');
3. $this->currency()->setCurrency($currency)->currency(1234.56);
4. // this returns '€ 1.234,56'

If you are using the helper without Zend_View then you can also use it directly.

Example #4 Direct usage

1. // our example currency
2. $currency = new Zend_Currency('de_AT');
4. // initiate the helper
5. $helper = new Zend_View_Helper_Currency($currency);
6. echo $helper->currency(1234.56); // this returns '€ 1.234,56'

As already seen, the currency() method is used to return the currency string. Just call it with the value you want to display as a currency. It also accepts some options which may be used to change the behaviour and output of the helper.

Example #5 Direct usage

1. // our example currency
2. $currency = new Zend_Currency('de_AT');
4. // initiate the helper
5. $helper = new Zend_View_Helper_Currency($currency);
6. echo $helper->currency(1234.56); // this returns '€ 1.234,56'
7. echo $helper->currency(1234.56, array ('precision' => 1));
8. // this returns '€ 1.234,6'

For details about the available options, search for Zend_Currency's toCurrency() method.

# Cycle Helper

The Cycle helper is used to alternate a set of values.

Example #6 Cycle Helper Basic Usage

To add elements to cycle just specify them in constructor or use assign(array $data) function

1. <?php foreach ($this->books as $book):?>
2. <tr style="background-color:<?php echo $this->cycle(array("#F0F0F0",
3. "#FFFFFF"))
4. ->next()?>">
5. <td><?php echo $this->escape($book['author']) ?></td>
6. </tr>
7. <?php endforeach;?>
9. // Moving in backwards order and assign function
10. $this->cycle()->assign(array("#F0F0F0","#FFFFFF"));
11. $this->cycle()->prev();
12. ?>

The output

1. <tr style="background-color:'#F0F0F0'">
2. <td>First</td>
3. </tr>
4. <tr style="background-color:'#FFFFFF'">
5. <td>Second</td>
6. </tr>

Example #7 Working with two or more cycles

To use two cycles you have to specify the names of cycles. Just set second parameter in cycle method. $this->cycle(array("#F0F0F0","#FFFFFF"),'cycle2'). You can also use setName($name) function.

1. <?php foreach ($this->books as $book):?>
2. <tr style="background-color:<?php echo $this->cycle(array("#F0F0F0",
3. "#FFFFFF"))
4. ->next()?>">
5. <td><?php echo $this->cycle(array(1,2,3),'number')->next()?></td>
6. <td><?php echo $this->escape($book['author'])?></td>
7. </tr>
8. <?php endforeach;?>

# Partial Helper

The Partial view helper is used to render a specified template within its own variable scope. The primary use is for reusable template fragments with which you do not need to worry about variable name clashes. Additionally, they allow you to specify partial view scripts from specific modules.

A sibling to the Partial, the PartialLoop view helper allows you to pass iterable data, and render a partial for each item.

> Note: PartialLoop Counter
> The PartialLoop view helper assigns a variable to the view named partialCounter which passes the current position of the array to the view script. This provides an easy way to have alternating colors on table rows for example.

Example #8 Basic Usage of Partials

Basic usage of partials is to render a template fragment in its own view scope. Consider the following partial script:

1. <?php // partial.phtml ?>
2. <ul>
3. <li>From: <?php echo $this->escape($this->from) ?></li>
4. <li>Subject: <?php echo $this->escape($this->subject) ?></li>
5. </ul>

You would then call it from your view script using the following:

1. <?php echo $this->partial('partial.phtml', array (
2. 'from' => 'Team Framework',
3. 'subject' => 'view partials')); ?>

Which would then render:

1. <ul>
2. <li>From: Team Framework</li>
3. <li>Subject: view partials</li>
4. </ul>

> Note: What is a model?
> A model used with the Partial view helper can be one of the following:

> - Array. If an array is passed, it should be associative, as its key/value pairs are assigned to the view with keys as view variables.

> - Object implementing toArray() method. If an object is passed an has a toArray() method, the results of toArray() will be assigned to the view object as view variables.

> - Standard object. Any other object will assign the results of object_get_vars() (essentially all public properties of the object) to the view object.

> If your model is an object, you may want to have it passed as an object to the partial script, instead of serializing it to an array of variables. You can do this by setting the 'objectKey' property of the appropriate helper:
> 1. // Tell partial to pass objects as 'model' variable
> 2. $view->partial()->setObjectKey('model');
> 4. // Tell partial to pass objects from partialLoop as 'model' variable
> 5. // in final partial view script:
> 6. $view->partialLoop()->setObjectKey('model');
> This technique is particularly useful when passing Zend_Db_Table_Rowsets to partialLoop(), as you then have full access to your row objects within the view scripts, allowing you to call methods on them (such as retrieving values from parent or dependent rows).

Example #9 Using PartialLoop to Render Iterable Models

Typically, you'll want to use partials in a loop, to render the same content fragment many times; this way you can put large blocks of repeated content or complex display logic into a single location. However this has a performance impact, as the partial helper needs to be invoked once for each iteration.

The PartialLoop view helper helps solve this issue. It allows you to pass an iterable item (array or object implementing Iterator) as the model. It then iterates over this, passing, the items to the partial script as the model. Items in the iterator may be any model the Partial view helper allows.

Let's assume the following partial view script:

1. <?php // partialLoop.phtml ?>
2. <dt><?php echo $this->key ?></dt>
3. <dd><?php echo $this->value ?></dd>

And the following "model":

1. $model = array (
2. array ('key' => 'Mammal', 'value' => 'Camel'),
3. array ('key' => 'Bird', 'value' => 'Penguin'),
4. array ('key' => 'Reptile', 'value' => 'Asp'),
5. array ('key' => 'Fish', 'value' => 'Flounder'),
6. );

In your view script, you could then invoke the PartialLoop helper:

1. <dl>
2. <?php echo $this->partialLoop('partialLoop.phtml', $model) ?>
3. </dl>

1. <dl>
2. <dt>Mammal</dt>
3. <dd>Camel</dd>
5. <dt>Bird</dt>
6. <dd>Penguin</dd>
8. <dt>Reptile</dt>
9. <dd>Asp</dd>
11. <dt>Fish</dt>
12. <dd>Flounder</dd>
13. </dl>

Example #10 Rendering Partials in Other Modules

Sometime a partial will exist in a different module. If you know the name of the module, you can pass it as the second argument to either partial() or partialLoop(), moving the $model argument to third position.

For instance, if there's a pager partial you wish to use that's in the 'list' module, you could grab it as follows:

1. <?php echo $this->partial('pager.phtml', 'list', $pagerData) ?>

In this way, you can re-use partials created specifically for other modules. That said, it's likely a better practice to put re-usable partials in shared view script paths.

# Placeholder Helper

The Placeholder view helper is used to persist content between view scripts and view instances. It also offers some useful features such as aggregating content, capturing view script content for later use, and adding pre- and post-text to content (and custom separators for aggregated content).

Example #11 Basic Usage of Placeholders

Basic usage of placeholders is to persist view data. Each invocation of the Placeholder helper expects a placeholder name; the helper then returns a placeholder container object that you can either manipulate or simply echo out.

1. <?php $this->placeholder('foo')->set("Some text for later") ?>
3. <?php
4. echo $this->placeholder('foo');
5. // outputs "Some text for later"
6. ?>

Example #12 Using Placeholders to Aggregate Content

Aggregating content via placeholders can be useful at times as well. For instance, your view script may have a variable array from which you wish to retrieve messages to display later; a later view script can then determine how those will be rendered.

The Placeholder view helper uses containers that extend ArrayObject, providing a rich featureset for manipulating arrays. In addition, it offers a variety of methods for formatting the content stored in the container:

- setPrefix($prefix) sets text with which to prefix the content. Use getPrefix() at any time to determine what the current setting is.

- setPostfix($prefix) sets text with which to append the content. Use getPostfix() at any time to determine what the current setting is.

- setSeparator($prefix) sets text with which to separate aggregated content. Use getSeparator() at any time to determine what the current setting is.

- setIndent($prefix) can be used to set an indentation value for content. If an integer is passed, that number of spaces will be used; if a string is passed, the string will be used. Use getIndent() at any time to determine what the current setting is.

1. <!-- first view script -->
2. <?php $this->placeholder('foo')->exchangeArray($this->data) ?>

1. <!-- later view script -->
2. <?php
3. $this->placeholder('foo')->setPrefix("<ul>\n <li>")
4. ->setSeparator("</li><li>\n")
5. ->setIndent(4)
6. ->setPostfix("</li></ul>\n");
7. ?>
9. <?php
10. echo $this->placeholder('foo');
11. // outputs as unordered list with pretty indentation
12. ?>

Because the Placeholder container objects extend ArrayObject, you can also assign content to a specific key in the container easily, instead of simply pushing it into the container. Keys may be accessed either as object properties or as array keys.

1. <?php $this->placeholder('foo')->bar = $this->data ?>
2. <?php echo $this->placeholder('foo')->bar ?>
4. <?php
5. $foo = $this->placeholder('foo');
6. echo $foo['bar'];
7. ?>

Example #13 Using Placeholders to Capture Content

Occasionally you may have content for a placeholder in a view script that is easiest to template; the Placeholder view helper allows you to capture arbitrary content for later rendering using the following API.

- captureStart($type, $key) begins capturing content.

  $type should be one of the Placeholder constants `APPEND` or `SET`. If `APPEND`, captured content is appended to the list of current content in the placeholder; if `SET`, captured content is used as the sole value of the placeholder (potentially replacing any previous content). By default, $type is `APPEND`.

  $key can be used to specify a specific key in the placeholder container to which you want content captured.

  captureStart() locks capturing until captureEnd() is called; you cannot nest capturing with the same placeholder container. Doing so will raise an exception.

- captureEnd() stops capturing content, and places it in the container object according to how captureStart() was called.

1. <!-- Default capture: append -->
2. <?php $this->placeholder('foo')->captureStart();
3. foreach ($this->data as $datum): ?>
4. <div class="foo">
5. <h2><?php echo $datum->title ?></h2>
6. <p><?php echo $datum->content ?></p>
7. </div>
8. <?php endforeach; ?>
9. <?php $this->placeholder('foo')->captureEnd() ?>
11. <?php echo $this->placeholder('foo') ?>

1. <!-- Capture to key -->
2. <?php $this->placeholder('foo')->captureStart('SET', 'data');
3. foreach ($this->data as $datum): ?>
4. <div class="foo">
5. <h2><?php echo $datum->title ?></h2>
6. <p><?php echo $datum->content ?></p>
7. </div>
8. <?php endforeach; ?>
9. <?php $this->placeholder('foo')->captureEnd() ?>
11. <?php echo $this->placeholder('foo')->data ?>

# Concrete Placeholder Implementations

Zend Framework ships with a number of "concrete" placeholder implementations. These are for commonly used placeholders: doctype, page title, and various <head> elements. In all cases, calling the placeholder with no arguments returns the element itself.

Documentation for each element is covered separately, as linked below:

- Doctype

- HeadLink

- HeadMeta

- HeadScript

- HeadStyle

- HeadTitle

- InlineScript

# Doctype Helper

Valid HTML and XHTML documents should include a `DOCTYPE` declaration. Besides being difficult to remember, these can also affect how certain elements in your document should be rendered (for instance, CDATA escaping in <script> and <style> elements.

The Doctype helper allows you to specify one of the following types:

- `XHTML11`

- `XHTML1_STRICT`

- `XHTML1_TRANSITIONAL`

- `XHTML1_FRAMESET`

- `XHTML1_RDFA`

- `XHTML_BASIC1`

- `HTML4_STRICT`

- `HTML4_LOOSE`

- `HTML4_FRAMESET`

- `HTML5`

You can also specify a custom doctype as long as it is well-formed.

The Doctype helper is a concrete implementation of the Placeholder helper.

Example #14 Doctype Helper Basic Usage

You may specify the doctype at any time. However, helpers that depend on the doctype for their output will recognize it only after you have set it, so the easiest approach is to specify it in your bootstrap:

1. $doctypeHelper = new Zend_View_Helper_Doctype();
2. $doctypeHelper->doctype('XHTML1_STRICT');

And then print it out on top of your layout script:

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

Example #15 Retrieving the Doctype

If you need to know the doctype, you can do so by calling getDoctype() on the object, which is returned by invoking the helper.

1. $doctype = $view->doctype()->getDoctype();

Typically, you'll simply want to know if the doctype is XHTML or not; for this, the isXhtml() method will suffice:

1. if ($view->doctype()->isXhtml()) {
2. // do something differently
3. }

You can also check if the doctype represents an HTML5 document.

1. if ($view->doctype()->isHtml5()) {
2. // do something differently
3. }

Example #16 Choosing a Doctype to Use with the Open Graph Protocol

To implement the » Open Graph Protocol, you may specify the XHTML1_RDFA doctype. This doctype allows a developer to use the » Resource Description Framework within an XHTML document.

1. $doctypeHelper = new Zend_View_Helper_Doctype();
2. $doctypeHelper->doctype('XHTML1_RDFA');

The RDFa doctype allows XHTML to validate when the 'property' meta tag attribute is used per the Open Graph Protocol spec. Example within a view script:

1. <?php echo $this->doctype('XHTML1_RDFA'); ?>
2. <html xmlns="http://www.w3.org/1999/xhtml"
3. xmlns:og="http://opengraphprotocol.org/schema/">
4. <head>
5. <meta property="og:type" content="musician" />

In the previous example, we set the property to og:type. The og references the Open Graph namespace we specified in the html tag. The content identifies the page as being about a musician. See the » Open Graph Protocol documentation for supported properties. The HeadMeta helper may be used to programmatically set these Open Graph Protocol meta tags.

Here is how you check if the doctype is set to XHTML1_RDFA:

1. <?php echo $this->doctype() ?>
2. <html xmlns="http://www.w3.org/1999/xhtml"
3. <?php if ($view->doctype()->isRdfa()): ?>
4. xmlns:og="http://opengraphprotocol.org/schema/"
5. xmlns:fb="http://www.facebook.com/2008/fbml"
6. <?php endif; ?>
7. >

# Gravatar View Helper

The Gravatar view helper is used to received avatars from Gravatar's service.

Example #17 Basic Usage of Gravatar View Helper

1. // From a view script (using XHTML DOCTYPE):
2. echo $this->gravatar('example@example.com');
4. /* results in the following output:
5. <img src="http://www.gravatar.com/avatar/23463b99b62a72f26ed677cc556c44e8?s=80&d=mm&r=g" />
6. */

> Note: Of course we can configure this helper. We can change height of image (by default it is 80px), and add CSS class or other attributes to image tag. The above simply shows the most basic usage.

Warning

# Use a valid email address!

The email address you provide the helper should be valid. This class does not validate the address (only the rating parameter). It is recommended to validate your email address within your model layer.

Example #18 Advanced Usage of Gravatar View Helper

There are several ways to configure the returned gravatar. In most cases, you may either pass an array of options as a second argument to the helper, or call methods on the returned object in order to configure it.

- The img_size option can be used to specify an alternate height; alternately, call setImgSize().

- The secure option can be used to force usage of SSL in the returned image URI by passing a boolean `true` value (or disabling SSL usage by passing `false`). Alternately, call the setSecure() method. (By default, the setting follows the same security as the current page request.)

- To add attributes to the image, pass an array of key/value pairs as the third argument to the helper, or call the setAttribs() method.

1. // Within the view script (using HTML DOCTYPE)
2. echo $this->gravatar('example@example.com',
3. array ('imgSize' => 90, 'defaultImg' => 'monsterid', 'secure' => true),
4. array ('class' => 'avatar', 'title' => 'Title for this image')
5. );
7. // Or use mutator methods
8. $this->gravatar()
9. ->setEmail('example@example.com')
10. ->setImgSize(90)
11. ->setDefaultImg(Zend_View_Helper_Gravatar::DEFAULT_MONSTERID)
12. ->setSecure(true)
13. ->setAttribs( array ('class' => 'avatar', 'title' => 'Title for this image'));
15. /* Both generate the following output:
16. <img class="avatar" title="Title for this image"
17. src="https://secure.gravatar.com/avatar/23463b99b62a72f26ed677cc556c44e8?s=90&d=monsterid&r=g" >
18. */

# Options

# Zend_Service_Gravatar Options

img_size

  An integer describing the height of the avatar, in pixels; defaults to "80".

default_img

  Image to return if the gravatar service is unable to match the email address provided. Defaults to "mm", the "mystery man" image.

rating

  Audience rating to confine returned images to. Defaults to "g"; may be one of "g", "pg", "r", or "x", in order of least offensive to most offensive.

secure

  Whether or not to load the image via an SSL connection. Defaults to the what is detected from the current request.

# HeadLink Helper

The HTML <link> element is increasingly used for linking a variety of resources for your site: stylesheets, feeds, favicons, trackbacks, and more. The HeadLink helper provides a simple interface for creating and aggregating these elements for later retrieval and output in your layout script.

The HeadLink helper has special methods for adding stylesheet links to its stack:

- appendStylesheet($href, $media, $conditionalStylesheet, $extras)

- offsetSetStylesheet($index, $href, $media, $conditionalStylesheet, $extras)

- prependStylesheet($href, $media, $conditionalStylesheet, $extras)

- setStylesheet($href, $media, $conditionalStylesheet, $extras)

The $media value defaults to 'screen', but may be any valid media value. $conditionalStylesheet is a string or boolean `FALSE`, and will be used at rendering time to determine if special comments should be included to prevent loading of the stylesheet on certain platforms. $extras is an array of any extra values that you want to be added to the tag.

Additionally, the HeadLink helper has special methods for adding 'alternate' links to its stack:

- appendAlternate($href, $type, $title, $extras)

- offsetSetAlternate($index, $href, $type, $title, $extras)

- prependAlternate($href, $type, $title, $extras)

- setAlternate($href, $type, $title, $extras)

The headLink() helper method allows specifying all attributes necessary for a <link> element, and allows you to also specify placement -- whether the new element replaces all others, prepends (top of stack), or appends (end of stack).

The HeadLink helper is a concrete implementation of the Placeholder helper.

Example #19 HeadLink Helper Basic Usage

You may specify a headLink at any time. Typically, you will specify global links in your layout script, and application specific links in your application view scripts. In your layout script, in the <head> section, you will then echo the helper to output it.

1. <?php // setting links in a view script:
2. $this->headLink()->appendStylesheet('/styles/basic.css')
3. ->headLink( array ('rel' => 'icon',
4. 'href' => '/img/favicon.ico'),
5. 'PREPEND')
6. ->prependStylesheet('/styles/moz.css',
7. 'screen',
8. true,
9. array ('id' => 'my_stylesheet'));
10. ?>
11. <?php // rendering the links: ?>
12. <?php echo $this->headLink() ?>

# HeadMeta Helper

The HTML <meta> element is used to provide meta information about your HTML document -- typically keywords, document character set, caching pragmas, etc. Meta tags may be either of the 'http-equiv' or 'name' types, must contain a 'content' attribute, and can also have either of the 'lang' or 'scheme' modifier attributes.

The HeadMeta helper supports the following methods for setting and adding meta tags:

- appendName($keyValue, $content, $conditionalName)

- offsetSetName($index, $keyValue, $content, $conditionalName)

- prependName($keyValue, $content, $conditionalName)

- setName($keyValue, $content, $modifiers)

- appendHttpEquiv($keyValue, $content, $conditionalHttpEquiv)

- offsetSetHttpEquiv($index, $keyValue, $content, $conditionalHttpEquiv)

- prependHttpEquiv($keyValue, $content, $conditionalHttpEquiv)

- setHttpEquiv($keyValue, $content, $modifiers)

- setCharset($charset)

The following methods are also supported with XHTML1_RDFA doctype set with the Doctype helper:

- appendProperty($property, $content, $modifiers)

- offsetSetProperty($index, $property, $content, $modifiers)

- prependProperty($property, $content, $modifiers)

- setProperty($property, $content, $modifiers)

The $keyValue item is used to define a value for the 'name' or 'http-equiv' key; $content is the value for the 'content' key, and $modifiers is an optional associative array that can contain keys for 'lang' and/or 'scheme'.

You may also set meta tags using the headMeta() helper method, which has the following signature: headMeta($content, $keyValue, $keyType = 'name', $modifiers = array(), $placement = 'APPEND'). $keyValue is the content for the key specified in $keyType, which should be either 'name' or 'http-equiv'. $keyType may also be specified as 'property' if the doctype has been set to XHTML1_RDFA. $placement can be 'SET' (overwrites all previously stored values), 'APPEND' (added to end of stack), or 'PREPEND' (added to top of stack).

HeadMeta overrides each of append(), offsetSet(), prepend(), and set() to enforce usage of the special methods as listed above. Internally, it stores each item as a stdClass token, which it later serializes using the itemToString() method. This allows you to perform checks on the items in the stack, and optionally modify these items by simply modifying the object returned.

The HeadMeta helper is a concrete implementation of the Placeholder helper.

Example #20 HeadMeta Helper Basic Usage

You may specify a new meta tag at any time. Typically, you will specify client-side caching rules or SEO keywords.

For instance, if you wish to specify SEO keywords, you'd be creating a meta name tag with the name 'keywords' and the content the keywords you wish to associate with your page:

1. // setting meta keywords
2. $this->headMeta()->appendName('keywords', 'framework, PHP, productivity');

If you wished to set some client-side caching rules, you'd set http-equiv tags with the rules you wish to enforce:

1. // disabling client-side cache
2. $this->headMeta()->appendHttpEquiv('expires',
3. 'Wed, 26 Feb 1997 08:21:57 GMT')
4. ->appendHttpEquiv('pragma', 'no-cache')
5. ->appendHttpEquiv('Cache-Control', 'no-cache');

Another popular use for meta tags is setting the content type, character set, and language:

1. // setting content type and character set
2. $this->headMeta()->appendHttpEquiv('Content-Type',
3. 'text/html; charset=UTF-8')
4. ->appendHttpEquiv('Content-Language', 'en-US');

If you are serving an HTML5 document, you should provide the character set like this:

1. // setting character set in HTML5
2. $this->headMeta()->setCharset('UTF-8'); // Will look like <meta charset="UTF-8">

As a final example, an easy way to display a transitional message before a redirect is using a "meta refresh":

1. // setting a meta refresh for 3 seconds to a new url:
2. $this->headMeta()->appendHttpEquiv('Refresh',
3. '3;URL=http://www.some.org/some.html');

When you're ready to place your meta tags in the layout, simply echo the helper:

1. <?php echo $this->headMeta() ?>

Example #21 HeadMeta Usage with XHTML1_RDFA doctype

Enabling the RDFa doctype with the Doctype helper enables the use of the 'property' attribute (in addition to the standard 'name' and 'http-equiv') with HeadMeta. This is commonly used with the Facebook » Open Graph Protocol.

For instance, you may specify an open graph page title and type as follows:

1. $this->doctype(Zend_View_Helper_Doctype::XHTML1_RDFA);
2. $this->headMeta()->setProperty('og:title', 'my article title');
3. $this->headMeta()->setProperty('og:type', 'article');
4. echo $this->headMeta();
6. // output is:
7. // <meta property="og:title" content="my article title" />
8. // <meta property="og:type" content="article" />

# HeadScript Helper

The HTML <script> element is used to either provide inline client-side scripting elements or link to a remote resource containing client-side scripting code. The HeadScript helper allows you to manage both.

The HeadScript helper supports the following methods for setting and adding scripts:

- appendFile($src, $type = 'text/javascript', $attrs = array())

- offsetSetFile($index, $src, $type = 'text/javascript', $attrs = array())

- prependFile($src, $type = 'text/javascript', $attrs = array())

- setFile($src, $type = 'text/javascript', $attrs = array())

- appendScript($script, $type = 'text/javascript', $attrs = array())

- offsetSetScript($index, $script, $type = 'text/javascript', $attrs = array())

- prependScript($script, $type = 'text/javascript', $attrs = array())

- setScript($script, $type = 'text/javascript', $attrs = array())

In the case of the * File() methods, $src is the remote location of the script to load; this is usually in the form of a URL or a path. For the * Script() methods, $script is the client-side scripting directives you wish to use in the element.

> Note: Setting Conditional Comments
> HeadScript allows you to wrap the script tag in conditional comments, which allows you to hide it from specific browsers. To add the conditional tags, pass the conditional value as part of the $attrs parameter in the method calls.

> Example #22 Headscript With Conditional Comments

> 1. // adding scripts
> 2. $this->headScript()->appendFile(
> 3. '/js/prototype.js',
> 4. 'text/javascript',
> 5. array ('conditional' => 'lt IE 7')
> 6. );

> Note: Preventing HTML style comments or CDATA wrapping of scripts
> By default HeadScript will wrap scripts with HTML comments or it wraps scripts with XHTML cdata. This behavior can be problematic when you intend to use the script tag in an alternative way by setting the type to something other then 'text/javascript'. To prevent such escaping, pass an noescape with a value of true as part of the $attrs parameter in the method calls.

> Example #23 Create an jQuery template with the headScript

> 1. // jquery template
> 2. $template = '<div class="book">{{:title}}</div>';
> 3. $this->headScript()->appendScript(
> 4. $template,
> 5. 'text/x-jquery-tmpl',
> 6. array ('id='tmpl-book', 'noescape' => true)
> 7. );

HeadScript also allows capturing scripts; this can be useful if you want to create the client-side script programmatically, and then place it elsewhere. The usage for this will be showed in an example below.

Finally, you can also use the headScript() method to quickly add script elements; the signature for this is headScript($mode = 'FILE', $spec, $placement = 'APPEND'). The $mode is either 'FILE' or 'SCRIPT', depending on if you're linking a script or defining one. $spec is either the script file to link or the script source itself. $placement should be either 'APPEND', 'PREPEND', or 'SET'.

HeadScript overrides each of append(), offsetSet(), prepend(), and set() to enforce usage of the special methods as listed above. Internally, it stores each item as a stdClass token, which it later serializes using the itemToString() method. This allows you to perform checks on the items in the stack, and optionally modify these items by simply modifying the object returned.

The HeadScript helper is a concrete implementation of the Placeholder helper.

> Note: Use InlineScript for HTML Body Scripts
> HeadScript's sibling helper, InlineScript, should be used when you wish to include scripts inline in the HTML body. Placing scripts at the end of your document is a good practice for speeding up delivery of your page, particularly when using 3rd party analytics scripts.

> Note: Arbitrary Attributes are Disabled by Default
> By default, HeadScript only will render <script> attributes that are blessed by the W3C. These include 'type', 'charset', 'defer', 'language', and 'src'. However, some javascript frameworks, notably » Dojo, utilize custom attributes in order to modify behavior. To allow such attributes, you can enable them via the setAllowArbitraryAttributes() method:

> 1. $this->headScript()->setAllowArbitraryAttributes(true);

Example #24 HeadScript Helper Basic Usage

You may specify a new script tag at any time. As noted above, these may be links to outside resource files or scripts themselves.

1. // adding scripts
2. $this->headScript()->appendFile('/js/prototype.js')
3. ->appendScript($onloadScript);

Order is often important with client-side scripting; you may need to ensure that libraries are loaded in a specific order due to dependencies each have; use the various append, prepend, and offsetSet directives to aid in this task:

1. // Putting scripts in order
3. // place at a particular offset to ensure loaded last
4. $this->headScript()->offsetSetFile(100, '/js/myfuncs.js');
6. // use scriptaculous effects (append uses next index, 101)
7. $this->headScript()->appendFile('/js/scriptaculous.js');
9. // but always have base prototype script load first:
10. $this->headScript()->prependFile('/js/prototype.js');

When you're finally ready to output all scripts in your layout script, simply echo the helper:

1. <?php echo $this->headScript() ?>

Example #25 Capturing Scripts Using the HeadScript Helper

Sometimes you need to generate client-side scripts programmatically. While you could use string concatenation, heredocs, and the like, often it's easier just to do so by creating the script and sprinkling in PHP tags. HeadScript lets you do just that, capturing it to the stack:

1. <?php $this->headScript()->captureStart() ?>
2. var action = '<?php echo $this->baseUrl ?>';
3. $('foo_form').action = action;
4. <?php $this->headScript()->captureEnd() ?>

The following assumptions are made:

- The script will be appended to the stack. If you wish for it to replace the stack or be added to the top, you will need to pass 'SET' or 'PREPEND', respectively, as the first argument to captureStart().

- The script MIME type is assumed to be 'text/javascript'; if you wish to specify a different type, you will need to pass it as the second argument to captureStart().

- If you wish to specify any additional attributes for the <script> tag, pass them in an array as the third argument to captureStart().

# HeadStyle Helper

The HTML <style> element is used to include CSS stylesheets inline in the HTML <head> element.

> Note: Use HeadLink to link CSS files
> HeadLink should be used to create <link> elements for including external stylesheets. HeadStyle is used when you wish to define your stylesheets inline.

The HeadStyle helper supports the following methods for setting and adding stylesheet declarations:

- appendStyle($content, $attributes = array())

- offsetSetStyle($index, $content, $attributes = array())

- prependStyle($content, $attributes = array())

- setStyle($content, $attributes = array())

In all cases, $content is the actual CSS declarations. $attributes are any additional attributes you wish to provide to the style tag: lang, title, media, or dir are all permissible.

> Note: Setting Conditional Comments
> HeadStyle allows you to wrap the style tag in conditional comments, which allows you to hide it from specific browsers. To add the conditional tags, pass the conditional value as part of the $attributes parameter in the method calls.

> Example #26 Headstyle With Conditional Comments

> 1. // adding scripts
> 2. $this->headStyle()->appendStyle($styles, array ('conditional' => 'lt IE 7'));

HeadStyle also allows capturing style declarations; this can be useful if you want to create the declarations programmatically, and then place them elsewhere. The usage for this will be showed in an example below.

Finally, you can also use the headStyle() method to quickly add declarations elements; the signature for this is headStyle($content$placement = 'APPEND', $attributes = array()). $placement should be either 'APPEND', 'PREPEND', or 'SET'.

HeadStyle overrides each of append(), offsetSet(), prepend(), and set() to enforce usage of the special methods as listed above. Internally, it stores each item as a stdClass token, which it later serializes using the itemToString() method. This allows you to perform checks on the items in the stack, and optionally modify these items by simply modifying the object returned.

The HeadStyle helper is a concrete implementation of the Placeholder helper.

> Note: UTF-8 encoding used by default
> By default, Zend Framework uses UTF-8 as its default encoding, and, specific to this case, Zend_View does as well. Character encoding can be set differently on the view object itself using the setEncoding() method (or the encoding instantiation parameter). However, since Zend_View_Interface does not define accessors for encoding, it's possible that if you are using a custom view implementation with this view helper, you will not have a getEncoding() method, which is what the view helper uses internally for determining the character set in which to encode.
> If you do not want to utilize UTF-8 in such a situation, you will need to implement a getEncoding() method in your custom view implementation.

Example #27 HeadStyle Helper Basic Usage

You may specify a new style tag at any time:

1. // adding styles
2. $this->headStyle()->appendStyle($styles);

Order is very important with CSS; you may need to ensure that declarations are loaded in a specific order due to the order of the cascade; use the various append, prepend, and offsetSet directives to aid in this task:

1. // Putting styles in order
3. // place at a particular offset:
4. $this->headStyle()->offsetSetStyle(100, $customStyles);
6. // place at end:
7. $this->headStyle()->appendStyle($finalStyles);
9. // place at beginning
10. $this->headStyle()->prependStyle($firstStyles);

When you're finally ready to output all style declarations in your layout script, simply echo the helper:

1. <?php echo $this->headStyle() ?>

Example #28 Capturing Style Declarations Using the HeadStyle Helper

Sometimes you need to generate CSS style declarations programmatically. While you could use string concatenation, heredocs, and the like, often it's easier just to do so by creating the styles and sprinkling in PHP tags. HeadStyle lets you do just that, capturing it to the stack:

1. <?php $this->headStyle()->captureStart() ?>
2. body {
3. background-color: <?php echo $this->bgColor ?>;
4. }
5. <?php $this->headStyle()->captureEnd() ?>

The following assumptions are made:

- The style declarations will be appended to the stack. If you wish for them to replace the stack or be added to the top, you will need to pass 'SET' or 'PREPEND', respectively, as the first argument to captureStart().

- If you wish to specify any additional attributes for the <style> tag, pass them in an array as the second argument to captureStart().

# HeadTitle Helper

The HTML <title> element is used to provide a title for an HTML document. The HeadTitle helper allows you to programmatically create and store the title for later retrieval and output.

The HeadTitle helper is a concrete implementation of the Placeholder helper. It overrides the toString() method to enforce generating a <title> element, and adds a headTitle() method for quick and easy setting and aggregation of title elements. The signature for that method is headTitle($title, $setType = null); by default, the value is appended to the stack (aggregating title segments) if left at null, but you may also specify either 'PREPEND' (place at top of stack) or 'SET' (overwrite stack).

Since setting the aggregating (attach) order on each call to headTitle can be cumbersome, you can set a default attach order by calling setDefaultAttachOrder() which is applied to all headTitle() calls unless you explicitly pass a different attach order as the second parameter.

Example #29 HeadTitle Helper Basic Usage

You may specify a title tag at any time. A typical usage would have you setting title segments for each level of depth in your application: site, controller, action, and potentially resource.

1. // setting the controller and action name as title segments:
2. $request = Zend_Controller_Front::getInstance()->getRequest();
3. $this->headTitle($request->getActionName())
4. ->headTitle($request->getControllerName());
6. // setting the site in the title; possibly in the layout script:
7. $this->headTitle('Zend Framework');
9. // setting a separator string for segments:
10. $this->headTitle()->setSeparator(' / ');

When you're finally ready to render the title in your layout script, simply echo the helper:

1. <!-- renders <action> / <controller> / Zend Framework -->
2. <?php echo $this->headTitle() ?>

# HTML Object Helpers

The HTML <object> element is used for embedding media like Flash or QuickTime in web pages. The object view helpers take care of embedding media with minimum effort.

There are four initial Object helpers:

- htmlFlash() Generates markup for embedding Flash files.

- htmlObject() Generates markup for embedding a custom Object.

- htmlPage() Generates markup for embedding other (X)HTML pages.

- htmlQuicktime() Generates markup for embedding QuickTime files.

All of these helpers share a similar interface. For this reason, this documentation will only contain examples of two of these helpers.

Example #30 Flash helper

Embedding Flash in your page using the helper is pretty straight-forward. The only required argument is the resource URI.

1. <?php echo $this->htmlFlash('/path/to/flash.swf'); ?>

This outputs the following HTML:

1. <object data="/path/to/flash.swf"
2. type="application/x-shockwave-flash"
3. classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
4. codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab">
5. </object>

Additionally you can specify attributes, parameters and content that can be rendered along with the <object>. This will be demonstrated using the htmlObject() helper.

Example #31 Customizing the object by passing additional arguments

The first argument in the object helpers is always required. It is the URI to the resource you want to embed. The second argument is only required in the htmlObject() helper. The other helpers already contain the correct value for this argument. The third argument is used for passing along attributes to the object element. It only accepts an array with key-value pairs. classid and codebase are examples of such attributes. The fourth argument also only takes a key-value array and uses them to create <param> elements. You will see an example of this shortly. Lastly, there is the option of providing additional content to the object. Now for an example which utilizes all arguments.

1. echo $this->htmlObject(
2. '/path/to/file.ext',
3. 'mime/type',
4. array (
5. 'attr1' => 'aval1',
6. 'attr2' => 'aval2'
7. ),
8. array (
9. 'param1' => 'pval1',
10. 'param2' => 'pval2'
11. ),
12. 'some content'
13. );
15. /*
16. This would output:
18. <object data="/path/to/file.ext" type="mime/type"
19. attr1="aval1" attr2="aval2">
20. <param name="param1" value="pval1" />
21. <param name="param2" value="pval2" />
22. some content
23. </object>
24. */

# InlineScript Helper

The HTML <script> element is used to either provide inline client-side scripting elements or link to a remote resource containing client-side scripting code. The InlineScript helper allows you to manage both. It is derived from HeadScript, and any method of that helper is available; however, use the inlineScript() method in place of headScript().

> Note: Use InlineScript for HTML Body Scripts
> InlineScript, should be used when you wish to include scripts inline in the HTML body. Placing scripts at the end of your document is a good practice for speeding up delivery of your page, particularly when using 3rd party analytics scripts.
> Some JS libraries need to be included in the HTML head; use HeadScript for those scripts.

# RenderToPlaceholder Helper

Renders a template (view script) and stores the rendered output as a placeholder variable for later use.

> Note: The helper uses the Placeholder helper and his Capture methods.

Example #32 Basic Usage of RenderToPlaceholder

1. <?php
2. // View script (backlink.phtml):
3. echo sprintf (
4. '<p class="older"><a href="%s">Older posts</a></p>',
5. $this->url( array ('controller' => 'index', 'action' => 'index'))
6. )
7. ?>
9. <?php
10. // Usage:
11. $this->renderToPlaceholder('backlink.phtml', 'link');
12. ?>
14. <?php
15. echo $this->placeholder('link');
16. // Output: <p class="older"><a href="index/index">Older posts</a></p>
17. ?>

# JSON Helper

When creating views that return JSON, it's important to also set the appropriate response header. The JSON view helper does exactly that. In addition, by default, it disables layouts (if currently enabled), as layouts generally aren't used with JSON responses.

The JSON helper sets the following header:

1. Content-Type: application/json

Most AJAX libraries look for this header when parsing responses to determine how to handle the content.

Usage of the JSON helper is very straightforward:

1. <?php echo $this->json($this->data) ?>

> Note: Keeping layouts and enabling encoding using Zend_Json_Expr
> Each method in the JSON helper accepts a second, optional argument. This second argument can be a boolean flag to enable or disable layouts, or an array of options that will be passed to Zend_Json::encode() and used internally to encode data.
> To keep layouts, the second parameter needs to be boolean `TRUE`. When the second parameter is an array, keeping layouts can be achieved by including a keepLayouts key with a value of a boolean `TRUE`.

> 1. // Boolean true as second argument enables layouts:
> 2. echo $this->json($this->data, true);
> 4. // Or boolean true as "keepLayouts" key:
> 5. echo $this->json($this->data, array ('keepLayouts' => true));
> Zend_Json::encode allows the encoding of native JSON expressions using Zend_Json_Expr objects. This option is disabled by default. To enable this option, pass a boolean `TRUE` to the enableJsonExprFinder key of the options array:
> 1. <?php echo $this->json($this->data, array (
> 2. 'enableJsonExprFinder' => true,
> 3. 'keepLayouts' => true,
> 4. )) ?>

> Note: Sending pre-encoded JSON
> By default, the JSON helper will JSON-encode the data provided to the helper's first parameter. If you wish to pass in data which has already been encoded into JSON, the third parameter needs to be set to boolean `FALSE`. When the second parameter is an array, disabling JSON encoding can be achived by including a encodeData key with the value of boolean `FALSE`:

> 1. // Boolean false as third argument disables internal JSON encoding of data
> 2. echo $this->json($this->data, false, false);
> 4. // Or boolean false as "encodeData" key:
> 5. echo $this->json($this->data, array ('encodeData' => false));

# Navigation Helpers

The navigation helpers are used for rendering navigational elements from Zend_Navigation_Container instances.

There are 5 built-in helpers:

- Breadcrumbs, used for rendering the path to the currently active page.

- Links, used for rendering navigational head links (e.g. <link rel="next" href="..." />)

- Menu, used for rendering menus.

- Sitemap, used for rendering sitemaps conforming to the » Sitemaps XML format.

- Navigation, used for proxying calls to other navigational helpers.

All built-in helpers extend Zend_View_Helper_Navigation_HelperAbstract, which adds integration with ACL and translation. The abstract class implements the interface Zend_View_Helper_Navigation_Helper, which defines the following methods:

- getContainer() and setContainer() gets and sets the navigation container the helper should operate on by default, and hasContainer() checks if the helper has container registered.

- getTranslator() and setTranslator() gets and sets the translator used for translating labels and titles. getUseTranslator() and setUseTranslator() controls whether the translator should be enabled. The method hasTranslator() checks if the helper has a translator registered.

- getAcl(), setAcl(), getRole() and setRole(), gets and sets ACL (Zend_Acl) instance and role ( String or Zend_Acl_Role_Interface) used for filtering out pages when rendering. getUseAcl() and setUseAcl() controls whether ACL should be enabled. The methods hasAcl() and hasRole() checks if the helper has an ACL instance or a role registered.

- __toString(), magic method to ensure that helpers can be rendered by echoing the helper instance directly.

- render(), must be implemented by concrete helpers to do the actual rendering.

In addition to the method stubs from the interface, the abstract class also implements the following methods:

- getIndent() and setIndent() gets and sets indentation. The setter accepts a String or an Integer . In the case of an Integer , the helper will use the given number of spaces for indentation. I.e., setIndent(4) means 4 initial spaces of indentation. Indentation can be specified for all helpers except the Sitemap helper.

- getMinDepth() and setMinDepth() gets and sets the minimum depth a page must have to be included by the helper. Setting `NULL` means no minimum depth.

- getMaxDepth() and setMaxDepth() gets and sets the maximum depth a page can have to be included by the helper. Setting `NULL` means no maximum depth.

- getRenderInvisible() and setRenderInvisible() gets and sets whether to render items that have been marked as invisible or not.

- __call() is used for proxying calls to the container registered in the helper, which means you can call methods on a helper as if it was a container. See example below.

- findActive($container, $minDepth, $maxDepth) is used for finding the deepest active page in the given container. If depths are not given, the method will use the values retrieved from getMinDepth() and getMaxDepth(). The deepest active page must be between $minDepth and $maxDepth inclusively. Returns an array containing a reference to the found page instance and the depth at which the page was found.

- htmlify() renders an 'a' HTML element from a Zend_Navigation_Page instance.

- accept() is used for determining if a page should be accepted when iterating containers. This method checks for page visibility and verifies that the helper's role is allowed access to the page's resource and privilege.

- The static method setDefaultAcl() is used for setting a default ACL object that will be used by helpers.

- The static method setDefaultRole() is used for setting a default ACL that will be used by helpers

If a navigation container is not explicitly set in a helper using $helper->setContainer($nav), the helper will look for a container instance with the key Zend_Navigation in the registry. If a container is not explicitly set or found in the registry, the helper will create an empty Zend_Navigation container when calling $helper->getContainer().

Example #33 Proxying calls to the navigation container

Navigation view helpers use the magic method __call() to proxy method calls to the navigation container that is registered in the view helper.

1. $this->navigation()->addPage( array (
2. 'type' => 'uri',
3. 'label' => 'New page'));

The call above will add a page to the container in the Navigation helper.

# Translation of labels and titles

The navigation helpers support translation of page labels and titles. You can set a translator of type Zend_Translate or Zend_Translate_Adapter in the helper using $helper->setTranslator($translator), or like with other I18n-enabled components; by adding the translator to the registry by using the key Zend_Translate.

If you want to disable translation, use $helper->setUseTranslator(false).

The proxy helper will inject its own translator to the helper it proxies to if the proxied helper doesn't already have a translator.

> Note: There is no translation in the sitemap helper, since there are no page labels or titles involved in an XML sitemap.

# Integration with ACL

All navigational view helpers support ACL inherently from the class Zend_View_Helper_Navigation_HelperAbstract. A Zend_Acl object can be assigned to a helper instance with `$helper->setAcl($acl)`, and role with `$helper->setRole('member')` or `$helper->setRole(new Zend_Acl_Role('member'))` . If ACL is used in the helper, the role in the helper must be allowed by the ACL to access a page's `resource` and/or have the page's `privilege` for the page to be included when rendering.

If a page is not accepted by ACL, any descendant page will also be excluded from rendering.

The proxy helper will inject its own ACL and role to the helper it proxies to if the proxied helper doesn't already have any.

The examples below all show how ACL affects rendering.

# Navigation setup used in examples

This example shows the setup of a navigation container for a fictional software company.

Notes on the setup:

- The domain for the site is `www.example.com`.

- Interesting page properties are marked with a comment.

- Unless otherwise is stated in other examples, the user is requesting the URL `http://www.example.com/products/server/faq/`, which translates to the page labeled `FAQ` under `Foo Server`.

- The assumed ACL and router setup is shown below the container setup.

1. /*
2. * Navigation container (config/array)
4. * Each element in the array will be passed to
5. * Zend_Navigation_Page::factory() when constructing
6. * the navigation container below.
7. */
8. $pages = array (
9. array (
10. 'label' => 'Home',
11. 'title' => 'Go Home',
12. 'module' => 'default',
13. 'controller' => 'index',
14. 'action' => 'index',
15. 'order' => -100 // make sure home is the first page
16. ),
17. array (
18. 'label' => 'Special offer this week only!',
19. 'module' => 'store',
20. 'controller' => 'offer',
21. 'action' => 'amazing',
22. 'visible' => false // not visible
23. ),
24. array (
25. 'label' => 'Products',
26. 'module' => 'products',
27. 'controller' => 'index',
28. 'action' => 'index',
29. 'pages' => array (
30. array (
31. 'label' => 'Foo Server',
32. 'module' => 'products',
33. 'controller' => 'server',
34. 'action' => 'index',
35. 'pages' => array (
36. array (
37. 'label' => 'FAQ',
38. 'module' => 'products',
39. 'controller' => 'server',
40. 'action' => 'faq',
41. 'rel' => array (
42. 'canonical' => 'http://www.example.com/?page=faq',
43. 'alternate' => array (
44. 'module' => 'products',
45. 'controller' => 'server',
46. 'action' => 'faq',
47. 'params' => array ('format' => 'xml')
48. )
49. )
50. ),
51. array (
52. 'label' => 'Editions',
53. 'module' => 'products',
54. 'controller' => 'server',
55. 'action' => 'editions'
56. ),
57. array (
58. 'label' => 'System Requirements',
59. 'module' => 'products',
60. 'controller' => 'server',
61. 'action' => 'requirements'
62. )
63. )
64. ),
65. array (
66. 'label' => 'Foo Studio',
67. 'module' => 'products',
68. 'controller' => 'studio',
69. 'action' => 'index',
70. 'pages' => array (
71. array (
72. 'label' => 'Customer Stories',
73. 'module' => 'products',
74. 'controller' => 'studio',
75. 'action' => 'customers'
76. ),
77. array (
78. 'label' => 'Support',
79. 'module' => 'prodcts',
80. 'controller' => 'studio',
81. 'action' => 'support'
82. )
83. )
84. )
85. )
86. ),
87. array (
88. 'label' => 'Company',
89. 'title' => 'About us',
90. 'module' => 'company',
91. 'controller' => 'about',
92. 'action' => 'index',
93. 'pages' => array (
94. array (
95. 'label' => 'Investor Relations',
96. 'module' => 'company',
97. 'controller' => 'about',
98. 'action' => 'investors'
99. ),
100. array (
101. 'label' => 'News',
102. 'class' => 'rss', // class
103. 'module' => 'company',
104. 'controller' => 'news',
105. 'action' => 'index',
106. 'pages' => array (
107. array (
108. 'label' => 'Press Releases',
109. 'module' => 'company',
110. 'controller' => 'news',
111. 'action' => 'press'
112. ),
113. array (
114. 'label' => 'Archive',
115. 'route' => 'archive', // route
116. 'module' => 'company',
117. 'controller' => 'news',
118. 'action' => 'archive'
119. )
120. )
121. )
122. )
123. ),
124. array (
125. 'label' => 'Community',
126. 'module' => 'community',
127. 'controller' => 'index',
128. 'action' => 'index',
129. 'pages' => array (
130. array (
131. 'label' => 'My Account',
132. 'module' => 'community',
133. 'controller' => 'account',
134. 'action' => 'index',
135. 'resource' => 'mvc:community.account' // resource
136. ),
137. array (
138. 'label' => 'Forums',
139. 'uri' => 'http://forums.example.com/',
140. 'class' => 'external' // class
141. )
142. )
143. ),
144. array (
145. 'label' => 'Administration',
146. 'module' => 'admin',
147. 'controller' => 'index',
148. 'action' => 'index',
149. 'resource' => 'mvc:admin', // resource
150. 'pages' => array (
151. array (
152. 'label' => 'Write new article',
153. 'module' => 'admin',
154. 'controller' => 'post',
155. 'aciton' => 'write'
156. )
157. )
158. )
159. );
161. // Create container from array
162. $container = new Zend_Navigation($pages);
164. // Store the container in the proxy helper:
165. $view->getHelper('navigation')->setContainer($container);
167. // ...or simply:
168. $view->navigation($container);
170. // ...or store it in the reigstry:
171. Zend_Registry::set('Zend_Navigation', $container);

In addition to the container above, the following setup is assumed:

1. // Setup router (default routes and 'archive' route):
2. $front = Zend_Controller_Front::getInstance();
3. $router = $front->getRouter();
4. $router->addDefaultRoutes();
5. $router->addRoute(
6. 'archive',
7. new Zend_Controller_Router_Route(
8. '/archive/:year',
9. array (
10. 'module' => 'company',
11. 'controller' => 'news',
12. 'action' => 'archive',
13. 'year' => (int) date ('Y') - 1
14. ),
15. array ('year' => '\d+')
16. )
17. );
19. // Setup ACL:
20. $acl = new Zend_Acl();
21. $acl->addRole(new Zend_Acl_Role('member'));
22. $acl->addRole(new Zend_Acl_Role('admin'));
23. $acl->add(new Zend_Acl_Resource('mvc:admin'));
24. $acl->add(new Zend_Acl_Resource('mvc:community.account'));
25. $acl->allow('member', 'mvc:community.account');
26. $acl->allow('admin', null);
28. // Store ACL and role in the proxy helper:
29. $view->navigation()->setAcl($acl)->setRole('member');
31. // ...or set default ACL and role statically:
32. Zend_View_Helper_Navigation_HelperAbstract::setDefaultAcl($acl);
33. Zend_View_Helper_Navigation_HelperAbstract::setDefaultRole('member');

# Breadcrumbs Helper

Breadcrumbs are used for indicating where in a sitemap a user is currently browsing, and are typically rendered like this: "You are here: Home > Products > FantasticProduct 1.0". The breadcrumbs helper follows the guidelines from » Breadcrumbs Pattern - Yahoo! Design Pattern Library, and allows simple customization (minimum/maximum depth, indentation, separator, and whether the last element should be linked), or rendering using a partial view script.

The Breadcrumbs helper works like this; it finds the deepest active page in a navigation container, and renders an upwards path to the root. For MVC pages, the "activeness" of a page is determined by inspecting the request object, as stated in the section on Zend_Navigation_Page_Mvc.

The helper sets the `minDepth` property to 1 by default, meaning breadcrumbs will not be rendered if the deepest active page is a root page. If `maxDepth` is specified, the helper will stop rendering when at the specified depth (e.g. stop at level 2 even if the deepest active page is on level 3).

Methods in the breadcrumbs helper:

- `{get|set}Separator()` gets/sets separator string that is used between breadcrumbs. Defualt is `' &gt; '`.

- `{get|set}LinkLast()` gets/sets whether the last breadcrumb should be rendered as an anchor or not. Default is `FALSE`.

- `{get|set}Partial()` gets/sets a partial view script that should be used for rendering breadcrumbs. If a partial view script is set, the helper's render() method will use the renderPartial() method. If no partial is set, the renderStraight() method is used. The helper expects the partial to be a String or an Array with two elements. If the partial is a String , it denotes the name of the partial script to use. If it is an Array , the first element will be used as the name of the partial view script, and the second element is the module where the script is found.

- renderStraight() is the default render method.

- renderPartial() is used for rendering using a partial view script.

Example #34 Rendering breadcrumbs

This example shows how to render breadcrumbs with default settings.

1. In a view script or layout:
2. <?php echo $this->navigation()->breadcrumbs(); ?>
4. The two calls above take advantage of the magic __toString() method,
5. and are equivalent to:
6. <?php echo $this->navigation()->breadcrumbs()->render(); ?>
8. Output:
9. <a href="/products">Products</a> &gt; <a href="/products/server">Foo Server</a> &gt; FAQ

Example #35 Specifying indentation

This example shows how to render breadcrumbs with initial indentation.

1. Rendering with 8 spaces indentation:
2. <?php echo $this->navigation()->breadcrumbs()->setIndent(8);?>
4. Output:
5. <a href="/products">Products</a> &gt; <a href="/products/server">Foo Server</a> &gt; FAQ

Example #36 Customize breadcrumbs output

This example shows how to customze breadcrumbs output by specifying various options.

1. In a view script or layout:
3. <?php
4. echo $this->navigation()
5. ->breadcrumbs()
6. ->setLinkLast(true) // link last page
7. ->setMaxDepth(1) // stop at level 1
8. ->setSeparator(' &#9654;' . PHP_EOL); // cool separator with newline
9. ?>
11. Output:
12. <a href="/products">Products</a> &#9654;
13. <a href="/products/server">Foo Server</a>
15. /////////////////////////////////////////////////////
17. Setting minimum depth required to render breadcrumbs:
19. <?php
20. $this->navigation()->breadcrumbs()->setMinDepth(10);
21. echo $this->navigation()->breadcrumbs();
22. ?>
24. Output:
25. Nothing, because the deepest active page is not at level 10 or deeper.

Example #37 Rendering breadcrumbs using a partial view script

This example shows how to render customized breadcrumbs using a partial vew script. By calling setPartial(), you can specify a partial view script that will be used when calling render(). When a partial is specified, the renderPartial() method will be called. This method will find the deepest active page and pass an array of pages that leads to the active page to the partial view script.

In a layout:

1. $partial = ;
2. echo $this->navigation()->breadcrumbs()
3. ->setPartial( array ('breadcrumbs.phtml', 'default'));

Contents of `application/modules/default/views/breadcrumbs.phtml`:

1. echo implode (', ', array_map (
2. create_function ('$a', 'return $a->getLabel();'),
3. $this->pages));

Output:

1. Products, Foo Server, FAQ

# Links Helper

The links helper is used for rendering HTML `LINK` elements. Links are used for describing document relationships of the currently active page. Read more about links and link types at » Document relationships: the LINK element (HTML4 W3C Rec.) and » Link types (HTML4 W3C Rec.) in the HTML4 W3C Recommendation.

There are two types of relations; forward and reverse, indicated by the keyords `'rel'` and `'rev'`. Most methods in the helper will take a $rel param, which must be either `'rel'` or `'rev'`. Most methods also take a $type param, which is used for specifying the link type (e.g. alternate, start, next, prev, chapter, etc).

Relationships can be added to page objects manually, or found by traversing the container registered in the helper. The method findRelation($page, $rel, $type) will first try to find the given $rel of $type from the $page by calling `$page->findRel($type)` or `$page->findRel($type)`. If the $page has a relation that can be converted to a page instance, that relation will be used. If the $page instance doesn't have the specified $type, the helper will look for a method in the helper named `search$rel$type` (e.g. searchRelNext() or searchRevAlternate()). If such a method exists, it will be used for determining the $page's relation by traversing the container.

Not all relations can be determined by traversing the container. These are the relations that will be found by searching:

- searchRelStart(), forward 'start' relation: the first page in the container.

- searchRelNext(), forward 'next' relation; finds the next page in the container, i.e. the page after the active page.

- searchRelPrev(), forward 'prev' relation; finds the previous page, i.e. the page before the active page.

- searchRelChapter(), forward 'chapter' relations; finds all pages on level 0 except the 'start' relation or the active page if it's on level 0.

- searchRelSection(), forward 'section' relations; finds all child pages of the active page if the active page is on level 0 (a 'chapter').

- searchRelSubsection(), forward 'subsection' relations; finds all child pages of the active page if the active pages is on level 1 (a 'section').

- searchRevSection(), reverse 'section' relation; finds the parent of the active page if the active page is on level 1 (a 'section').

- searchRevSubsection(), reverse 'subsection' relation; finds the parent of the active page if the active page is on level 2 (a 'subsection').

> Note: When looking for relations in the page instance (`$page->getRel($type)` or `$page->getRev($type)`), the helper accepts the values of type String , Array , Zend_Config, or Zend_Navigation_Page. If a string is found, it will be converted to a Zend_Navigation_Page_Uri. If an array or a config is found, it will be converted to one or several page instances. If the first key of the array/config is numeric, it will be considered to contain several pages, and each element will be passed to the page factory. If the first key is not numeric, the array/config will be passed to the page factory directly, and a single page will be returned.

The helper also supports magic methods for finding relations. E.g. to find forward alternate relations, call `$helper->findRelAlternate($page)`, and to find reverse section relations, call `$helper->findRevSection($page)`. Those calls correspond to `$helper->findRelation($page, 'rel', 'alternate');` and `$helper->findRelation($page, 'rev', 'section');` respectively.

To customize which relations should be rendered, the helper uses a render flag. The render flag is an integer value, and will be used in a » bitwse `and` (`&`) operation against the helper's render constants to determine if the relation that belongs to the render constant should be rendered.

See the example below for more information.

- `Zend_View_Helper_Navigation_Link::RENDER_ALTERNATE`

- `Zend_View_Helper_Navigation_Link::RENDER_STYLESHEET`

- `Zend_View_Helper_Navigation_Link::RENDER_START`

- `Zend_View_Helper_Navigation_Link::RENDER_NEXT`

- `Zend_View_Helper_Navigation_Link::RENDER_PREV`

- `Zend_View_Helper_Navigation_Link::RENDER_CONTENTS`

- `Zend_View_Helper_Navigation_Link::RENDER_INDEX`

- `Zend_View_Helper_Navigation_Link::RENDER_GLOSSARY`

- `Zend_View_Helper_Navigation_Link::RENDER_COPYRIGHT`

- `Zend_View_Helper_Navigation_Link::RENDER_CHAPTER`

- `Zend_View_Helper_Navigation_Link::RENDER_SECTION`

- `Zend_View_Helper_Navigation_Link::RENDER_SUBSECTION`

- `Zend_View_Helper_Navigation_Link::RENDER_APPENDIX`

- `Zend_View_Helper_Navigation_Link::RENDER_HELP`

- `Zend_View_Helper_Navigation_Link::RENDER_BOOKMARK`

- `Zend_View_Helper_Navigation_Link::RENDER_CUSTOM`

- `Zend_View_Helper_Navigation_Link::RENDER_ALL`

The constants from `RENDER_ALTERNATE` to `RENDER_BOOKMARK` denote standard HTML link types. `RENDER_CUSTOM` denotes non-standard relations that specified in pages. `RENDER_ALL` denotes standard and non-standard relations.

Methods in the links helper:

- `{get|set}RenderFlag()` gets/sets the render flag. Default is `RENDER_ALL`. See examples below on how to set the render flag.

- findAllRelations() finds all relations of all types for a given page.

- findRelation() finds all relations of a given type from a given page.

- `searchRel{Start|Next|Prev|Chapter|Section|Subsection}()` traverses a container to find forward relations to the start page, the next page, the previous page, chapters, sections, and subsections.

- `searchRev{Section|Subsection}()` traverses a container to find reverse relations to sections or subsections.

- renderLink() renders a single `link` element.

Example #38 Specify relations in pages

This example shows how to specify relations in pages.

1. $container = new Zend_Navigation( array (
2. array (
3. 'label' => 'Relations using strings',
4. 'rel' => array (
5. 'alternate' => 'http://www.example.org/'
6. ),
7. 'rev' => array (
8. 'alternate' => 'http://www.example.net/'
9. )
10. ),
11. array (
12. 'label' => 'Relations using arrays',
13. 'rel' => array (
14. 'alternate' => array (
15. 'label' => 'Example.org',
16. 'uri' => 'http://www.example.org/'
17. )
18. )
19. ),
20. array (
21. 'label' => 'Relations using configs',
22. 'rel' => array (
23. 'alternate' => new Zend_Config( array (
24. 'label' => 'Example.org',
25. 'uri' => 'http://www.example.org/'
26. ))
27. )
28. ),
29. array (
30. 'label' => 'Relations using pages instance',
31. 'rel' => array (
32. 'alternate' => Zend_Navigation_Page::factory( array (
33. 'label' => 'Example.org',
34. 'uri' => 'http://www.example.org/'
35. ))
36. )
37. )
38. ));

Example #39 Default rendering of links

This example shows how to render a menu from a container registered/found in the view helper.

1. In a view script or layout:
2. <?php echo $this->view->navigation()->links(); ?>
4. Output:
5. <link rel="alternate" href="/products/server/faq/format/xml">
6. <link rel="start" href="/" title="Home">
7. <link rel="next" href="/products/server/editions" title="Editions">
8. <link rel="prev" href="/products/server" title="Foo Server">
9. <link rel="chapter" href="/products" title="Products">
10. <link rel="chapter" href="/company/about" title="Company">
11. <link rel="chapter" href="/community" title="Community">
12. <link rel="canonical" href="http://www.example.com/?page=server-faq">
13. <link rev="subsection" href="/products/server" title="Foo Server">

Example #40 Specify which relations to render

This example shows how to specify which relations to find and render.

1. Render only start, next, and prev:
2. $helper->setRenderFlag(Zend_View_Helper_Navigation_Links::RENDER_START |
3. Zend_View_Helper_Navigation_Links::RENDER_NEXT |
4. Zend_View_Helper_Navigation_Links::RENDER_PREV);
6. Output:
7. <link rel="start" href="/" title="Home">
8. <link rel="next" href="/products/server/editions" title="Editions">
9. <link rel="prev" href="/products/server" title="Foo Server">

1. Render only native link types:
2. $helper->setRenderFlag(Zend_View_Helper_Navigation_Links::RENDER_ALL ^
3. Zend_View_Helper_Navigation_Links::RENDER_CUSTOM);
5. Output:
6. <link rel="alternate" href="/products/server/faq/format/xml">
7. <link rel="start" href="/" title="Home">
8. <link rel="next" href="/products/server/editions" title="Editions">
9. <link rel="prev" href="/products/server" title="Foo Server">
10. <link rel="chapter" href="/products" title="Products">
11. <link rel="chapter" href="/company/about" title="Company">
12. <link rel="chapter" href="/community" title="Community">
13. <link rev="subsection" href="/products/server" title="Foo Server">

1. Render all but chapter:
2. $helper->setRenderFlag(Zend_View_Helper_Navigation_Links::RENDER_ALL ^
3. Zend_View_Helper_Navigation_Links::RENDER_CHAPTER);
5. Output:
6. <link rel="alternate" href="/products/server/faq/format/xml">
7. <link rel="start" href="/" title="Home">
8. <link rel="next" href="/products/server/editions" title="Editions">
9. <link rel="prev" href="/products/server" title="Foo Server">
10. <link rel="canonical" href="http://www.example.com/?page=server-faq">
11. <link rev="subsection" href="/products/server" title="Foo Server">

# Menu Helper

The Menu helper is used for rendering menus from navigation containers. By default, the menu will be rendered using HTML `UL` and `LI` tags, but the helper also allows using a partial view script.

Methods in the Menu helper:

- `{get|set}UlClass()` gets/sets the CSS class used in renderMenu().

- `{get|set}ActiveClass()` gets/sets the CSS class for the active elements when rendering.

- `{get|set}OnlyActiveBranch()` gets/sets a flag specifying whether only the active branch of a container should be rendered.

- `{get|set}ExpandSiblingNodesOfActiveBranch()` gets/sets a flag specifying whether the sibling nodes of all nodes in the active branch should also be expanded and rendered.

- `{get|set}RenderParents()` gets/sets a flag specifying whether parents should be rendered when only rendering active branch of a container. If set to `FALSE`, only the deepest active menu will be rendered.

- `{get|set}Partial()` gets/sets a partial view script that should be used for rendering menu. If a partial view script is set, the helper's render() method will use the renderPartial() method. If no partial is set, the renderMenu() method is used. The helper expects the partial to be a String or an Array with two elements. If the partial is a String , it denotes the name of the partial script to use. If it is an Array , the first element will be used as the name of the partial view script, and the second element is the module where the script is found.

- htmlify() overrides the method from the abstract class to return `span` elements if the page has no `href`.

- renderMenu($container = null, $options = array()) is the default render method, and will render a container as a HTML `UL` list.

  If $container is not given, the container registered in the helper will be rendered.

  $options is used for overriding options specified temporarily without rsetting the values in the helper instance. It is an associative array where each key corresponds to an option in the helper.

  Recognized options:

  - `indent`; indentation. Expects a String or an `int` value.

  - `minDepth`; minimum depth. Expcects an `int` or `NULL` (no minimum depth).

  - `maxDepth`; maximum depth. Expcects an `int` or `NULL` (no maximum depth).

  - `ulClass`; CSS class for `ul` element. Expects a String .

  - `activeClass`; CSS class for for the active elements when rendering. Expects a String .

  - `onlyActiveBranch`; whether only active branch should be rendered. Expects a Boolean value.

  - `expandSiblingNodesOfActiveBranch`; whether the sibling nodes of nodes in the active branch should be expanded and rendered. Expects a Boolean value.

  - `renderParents`; whether parents should be rendered if only rendering active branch. Expects a Boolean value.

  If an option is not given, the value set in the helper will be used.

- renderPartial() is used for rendering the menu using a partial view script.

- renderSubMenu() renders the deepest menu level of a container's active branch.

Example #41 Rendering a menu

This example shows how to render a menu from a container registered/found in the view helper. Notice how pages are filtered out based on visibility and ACL.

1. In a view script or layout:
2. <?php echo $this->navigation()->menu()->render() ?>
4. Or simply:
5. <?php echo $this->navigation()->menu() ?>
7. Output:
8. <ul class="navigation">
9. <li>
10. <a title="Go Home" href="/">Home</a>
11. </li>
12. <li class="active">
13. <a href="/products">Products</a>
14. <ul>
15. <li class="active">
16. <a href="/products/server">Foo Server</a>
17. <ul>
18. <li class="active">
19. <a href="/products/server/faq">FAQ</a>
20. </li>
21. <li>
22. <a href="/products/server/editions">Editions</a>
23. </li>
24. <li>
25. <a href="/products/server/requirements">System Requirements</a>
26. </li>
27. </ul>
28. </li>
29. <li>
30. <a href="/products/studio">Foo Studio</a>
31. <ul>
32. <li>
33. <a href="/products/studio/customers">Customer Stories</a>
34. </li>
35. <li>
36. <a href="/prodcts/studio/support">Support</a>
37. </li>
38. </ul>
39. </li>
40. </ul>
41. </li>
42. <li>
43. <a title="About us" href="/company/about">Company</a>
44. <ul>
45. <li>
46. <a href="/company/about/investors">Investor Relations</a>
47. </li>
48. <li>
49. <a class="rss" href="/company/news">News</a>
50. <ul>
51. <li>
52. <a href="/company/news/press">Press Releases</a>
53. </li>
54. <li>
55. <a href="/archive">Archive</a>
56. </li>
57. </ul>
58. </li>
59. </ul>
60. </li>
61. <li>
62. <a href="/community">Community</a>
63. <ul>
64. <li>
65. <a href="/community/account">My Account</a>
66. </li>
67. <li>
68. <a class="external" href="http://forums.example.com/">Forums</a>
69. </li>
70. </ul>
71. </li>
72. </ul>

Example #42 Calling renderMenu() directly

This example shows how to render a menu that is not registered in the view helper by calling the renderMenu() directly and specifying a few options.

1. <?php
2. // render only the 'Community' menu
3. $community = $this->navigation()->findOneByLabel('Community');
4. $options = array (
5. 'indent' => 16,
6. 'ulClass' => 'community'
7. );
8. echo $this->navigation()
9. ->menu()
10. ->renderMenu($community, $options);
11. ?>
12. Output:
13. <ul class="community">
14. <li>
15. <a href="/community/account">My Account</a>
16. </li>
17. <li>
18. <a class="external" href="http://forums.example.com/">Forums</a>
19. </li>
20. </ul>

Example #43 Rendering the deepest active menu

This example shows how the renderSubMenu() will render the deepest sub menu of the active branch.

Calling renderSubMenu($container, $ulClass, $indent) is equivalent to calling renderMenu($container, $options) with the following options:

1. array (
2. 'ulClass' => $ulClass,
3. 'indent' => $indent,
4. 'minDepth' => null,
5. 'maxDepth' => null,
6. 'onlyActiveBranch' => true,
7. 'renderParents' => false
8. );

1. <?php
2. echo $this->navigation()
3. ->menu()
4. ->renderSubMenu(null, 'sidebar', 4);
5. ?>
7. The output will be the same if 'FAQ' or 'Foo Server' is active:
8. <ul class="sidebar">
9. <li class="active">
10. <a href="/products/server/faq">FAQ</a>
11. </li>
12. <li>
13. <a href="/products/server/editions">Editions</a>
14. </li>
15. <li>
16. <a href="/products/server/requirements">System Requirements</a>
17. </li>
18. </ul>

Example #44 Rendering a menu with maximum depth

1. <?php
2. echo $this->navigation()
3. ->menu()
4. ->setMaxDepth(1);
5. ?>
7. Output:
8. <ul class="navigation">
9. <li>
10. <a title="Go Home" href="/">Home</a>
11. </li>
12. <li class="active">
13. <a href="/products">Products</a>
14. <ul>
15. <li class="active">
16. <a href="/products/server">Foo Server</a>
17. </li>
18. <li>
19. <a href="/products/studio">Foo Studio</a>
20. </li>
21. </ul>
22. </li>
23. <li>
24. <a title="About us" href="/company/about">Company</a>
25. <ul>
26. <li>
27. <a href="/company/about/investors">Investor Relations</a>
28. </li>
29. <li>
30. <a class="rss" href="/company/news">News</a>
31. </li>
32. </ul>
33. </li>
34. <li>
35. <a href="/community">Community</a>
36. <ul>
37. <li>
38. <a href="/community/account">My Account</a>
39. </li>
40. <li>
41. <a class="external" href="http://forums.example.com/">Forums</a>
42. </li>
43. </ul>
44. </li>
45. </ul>

Example #45 Rendering a menu with minimum depth

1. <?php
2. echo $this->navigation()
3. ->menu()
4. ->setMinDepth(1);
5. ?>
7. Output:
8. <ul class="navigation">
9. <li class="active">
10. <a href="/products/server">Foo Server</a>
11. <ul>
12. <li class="active">
13. <a href="/products/server/faq">FAQ</a>
14. </li>
15. <li>
16. <a href="/products/server/editions">Editions</a>
17. </li>
18. <li>
19. <a href="/products/server/requirements">System Requirements</a>
20. </li>
21. </ul>
22. </li>
23. <li>
24. <a href="/products/studio">Foo Studio</a>
25. <ul>
26. <li>
27. <a href="/products/studio/customers">Customer Stories</a>
28. </li>
29. <li>
30. <a href="/prodcts/studio/support">Support</a>
31. </li>
32. </ul>
33. </li>
34. <li>
35. <a href="/company/about/investors">Investor Relations</a>
36. </li>
37. <li>
38. <a class="rss" href="/company/news">News</a>
39. <ul>
40. <li>
41. <a href="/company/news/press">Press Releases</a>
42. </li>
43. <li>
44. <a href="/archive">Archive</a>
45. </li>
46. </ul>
47. </li>
48. <li>
49. <a href="/community/account">My Account</a>
50. </li>
51. <li>
52. <a class="external" href="http://forums.example.com/">Forums</a>
53. </li>
54. </ul>

Example #46 Rendering only the active branch of a menu

1. <?php
2. echo $this->navigation()
3. ->menu()
4. ->setOnlyActiveBranch(true);
5. ?>
7. Output:
8. <ul class="navigation">
9. <li class="active">
10. <a href="/products">Products</a>
11. <ul>
12. <li class="active">
13. <a href="/products/server">Foo Server</a>
14. <ul>
15. <li class="active">
16. <a href="/products/server/faq">FAQ</a>
17. </li>
18. <li>
19. <a href="/products/server/editions">Editions</a>
20. </li>
21. <li>
22. <a href="/products/server/requirements">System Requirements</a>
23. </li>
24. </ul>
25. </li>
26. </ul>
27. </li>
28. </ul>

Example #47 Rendering only the active branch of a menu with minimum depth

1. <?php
2. echo $this->navigation()
3. ->menu()
4. ->setOnlyActiveBranch(true)
5. ->setMinDepth(1);
6. ?>
8. Output:
9. <ul class="navigation">
10. <li class="active">
11. <a href="/products/server">Foo Server</a>
12. <ul>
13. <li class="active">
14. <a href="/products/server/faq">FAQ</a>
15. </li>
16. <li>
17. <a href="/products/server/editions">Editions</a>
18. </li>
19. <li>
20. <a href="/products/server/requirements">System Requirements</a>
21. </li>
22. </ul>
23. </li>
24. </ul>

Example #48 Rendering only the active branch of a menu with maximum depth

1. <?php
2. echo $this->navigation()
3. ->menu()
4. ->setOnlyActiveBranch(true)
5. ->setMaxDepth(1);
6. ?>
8. Output:
9. <ul class="navigation">
10. <li class="active">
11. <a href="/products">Products</a>
12. <ul>
13. <li class="active">
14. <a href="/products/server">Foo Server</a>
15. </li>
16. <li>
17. <a href="/products/studio">Foo Studio</a>
18. </li>
19. </ul>
20. </li>
21. </ul>

Example #49 Rendering only the active branch of a menu with maximum depth and no parents

1. <?php
2. echo $this->navigation()
3. ->menu()
4. ->setOnlyActiveBranch(true)
5. ->setRenderParents(false)
6. ->setMaxDepth(1);
7. ?>
9. Output:
10. <ul class="navigation">
11. <li class="active">
12. <a href="/products/server">Foo Server</a>
13. </li>
14. <li>
15. <a href="/products/studio">Foo Studio</a>
16. </li>
17. </ul>

Example #50 Rendering a custom menu using a partial view script

This example shows how to render a custom menu using a partial vew script. By calling setPartial(), you can specify a partial view script that will be used when calling render(). When a partial is specified, the renderPartial() method will be called. This method will assign the container to the view with the key `container`.

In a layout:

1. $partial = array ('menu.phtml', 'default');
2. $this->navigation()->menu()->setPartial($partial);
3. echo $this->navigation()->menu()->render();

In application/modules/default/views/menu.phtml:

1. foreach ($this->container as $page) {
2. echo $this->navigation()->menu()->htmlify($page), PHP_EOL;
3. }

Output:

1. <a title="Go Home" href="/">Home</a>
2. <a href="/products">Products</a>
3. <a title="About us" href="/company/about">Company</a>
4. <a href="/community">Community</a>

Example #51 Rendering only the active branch and all siblings of the active branch

1. echo $this->navigation()
2. ->menu()
3. ->setExpandSiblingNodesOfActiveBranch(true);

Output:

1. <ul class="navigation">
2. <li>
3. <a title="Go Home" href="/">Home</a>
4. </li>
5. <li class="active">
6. <a href="/products">Products</a>
7. <ul>
8. <li class="active">
9. <a href="/products/server">Foo Server</a>
10. <ul>
11. <li class="active">
12. <a href="/products/server/faq">FAQ</a>
13. </li>
14. <li>
15. <a href="/products/server/editions">Editions</a>
16. </li>
17. <li>
18. <a href="/products/server/requirements">System Requirements</a>
19. </li>
20. </ul>
21. </li>
22. <li>
23. <a href="/products/studio">Foo Studio</a>
24. </li>
25. </ul>
26. </li>
27. <li>
28. <a title="About us" href="/company/about">Company</a>
29. </li>
30. <li>
31. <a href="/community">Community</a>
32. </li>
33. </ul>

# Sitemap Helper

The Sitemap helper is used for generating XML sitemaps, as defined by the » Sitemaps XML format. Read more about » Sitemaps on Wikpedia.

By default, the sitemap helper uses sitemap validators to validate each element that is rendered. This can be disabled by calling `$helper->setUseSitemapValidators(false)`.

> Note: If you disable sitemap validators, the custom properties (see table) are not validated at all.

The sitemap helper also supports » Sitemap XSD Schema validation of the generated sitemap. This is disabled by default, since it will require a request to the Schema file. It can be enabled with `$helper->setUseSchemaValidation(true)`.

Sitemap XML elements
Element | Description
--- | ---
`loc` | Absolute URL to page. An absolute URL will be generated by the helper.
`lastmod` | The date of last modification of the file, in » W3C Datetime format. This time portion can be omitted if desired, and only use YYYY-MM-DD. The helper will try to retrieve the `lastmod` value from the page's custom property `lastmod` if it is set in the page. If the value is not a valid date, it is ignored.

`changefreq`

How frequently the page is likely to change. This value provides general information to search engines and may not correlate exactly to how often they crawl the page. Valid values are:

- always

- hourly

- daily

- weekly

- monthly

- yearly

- never

The helper will try to retrieve the `changefreq` value from the page's custom property `changefreq` if it is set in the page. If the value is not valid, it is ignored.

`priority` | The priority of this URL relative to other URLs on your site. Valid values range from 0.0 to 1.0. The helper will try to retrieve the `priority` value from the page's custom property `priority` if it is set in the page. If the value is not valid, it is ignored.

Methods in the sitemap helper:

- `{get|set}FormatOutput()` gets/sets a flag indicating whether XML output should be formatted. This corresponds to the `formatOutput` property of the native DOMDocument class. Read more at » PHP: DOMDocument - Manual. Default is `FALSE`.

- `{get|set}UseXmlDeclaration()` gets/sets a flag indicating whether the XML declaration should be included when rendering. Default is `TRUE`.

- `{get|set}UseSitemapValidators()` gets/sets a flag indicating whether sitemap validators should be used when generating the DOM sitemap. Default is `TRUE`.

- `{get|set}UseSchemaValidation()` gets/sets a flag indicating whether the helper should use XML Schema validation when generating the DOM sitemap. Default is `FALSE`. If `TRUE`.

- `{get|set}ServerUrl()` gets/sets server URL that will be prepended to non-absolute URLs in the url() method. If no server URL is specified, it will be determined by the helper.

- url() is used to generate absolute URLs to pages.

- getDomSitemap() generates a DOMDocument from a given container.

Example #52 Rendering an XML sitemap

This example shows how to render an XML sitemap based on the setup we did further up.

1. // In a view script or layout:
3. // format output
4. $this->navigation()
5. ->sitemap()
6. ->setFormatOutput(true); // default is false
8. // other possible methods:
9. // ->setUseXmlDeclaration(false); // default is true
10. // ->setServerUrl('http://my.otherhost.com');
11. // default is to detect automatically
13. // print sitemap
14. echo $this->navigation()->sitemap();

Notice how pages that are invisible or pages with ACL roles incompatible with the view helper are filtered out:

1. <?xml version="1.0" encoding="UTF-8"?>
2. <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
3. <url>
4. <loc>http://www.example.com/</loc>
5. </url>
6. <url>
7. <loc>http://www.example.com/products</loc>
8. </url>
9. <url>
10. <loc>http://www.example.com/products/server</loc>
11. </url>
12. <url>
13. <loc>http://www.example.com/products/server/faq</loc>
14. </url>
15. <url>
16. <loc>http://www.example.com/products/server/editions</loc>
17. </url>
18. <url>
19. <loc>http://www.example.com/products/server/requirements</loc>
20. </url>
21. <url>
22. <loc>http://www.example.com/products/studio</loc>
23. </url>
24. <url>
25. <loc>http://www.example.com/products/studio/customers</loc>
26. </url>
27. <url>
28. <loc>http://www.example.com/prodcts/studio/support</loc>
29. </url>
30. <url>
31. <loc>http://www.example.com/company/about</loc>
32. </url>
33. <url>
34. <loc>http://www.example.com/company/about/investors</loc>
35. </url>
36. <url>
37. <loc>http://www.example.com/company/news</loc>
38. </url>
39. <url>
40. <loc>http://www.example.com/company/news/press</loc>
41. </url>
42. <url>
43. <loc>http://www.example.com/archive</loc>
44. </url>
45. <url>
46. <loc>http://www.example.com/community</loc>
47. </url>
48. <url>
49. <loc>http://www.example.com/community/account</loc>
50. </url>
51. <url>
52. <loc>http://forums.example.com/</loc>
53. </url>
54. </urlset>

Render the sitemap using no ACL role (should filter out /community/account):

1. echo $this->navigation()
2. ->sitemap()
3. ->setFormatOutput(true)
4. ->setRole();

1. <?xml version="1.0" encoding="UTF-8"?>
2. <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
3. <url>
4. <loc>http://www.example.com/</loc>
5. </url>
6. <url>
7. <loc>http://www.example.com/products</loc>
8. </url>
9. <url>
10. <loc>http://www.example.com/products/server</loc>
11. </url>
12. <url>
13. <loc>http://www.example.com/products/server/faq</loc>
14. </url>
15. <url>
16. <loc>http://www.example.com/products/server/editions</loc>
17. </url>
18. <url>
19. <loc>http://www.example.com/products/server/requirements</loc>
20. </url>
21. <url>
22. <loc>http://www.example.com/products/studio</loc>
23. </url>
24. <url>
25. <loc>http://www.example.com/products/studio/customers</loc>
26. </url>
27. <url>
28. <loc>http://www.example.com/prodcts/studio/support</loc>
29. </url>
30. <url>
31. <loc>http://www.example.com/company/about</loc>
32. </url>
33. <url>
34. <loc>http://www.example.com/company/about/investors</loc>
35. </url>
36. <url>
37. <loc>http://www.example.com/company/news</loc>
38. </url>
39. <url>
40. <loc>http://www.example.com/company/news/press</loc>
41. </url>
42. <url>
43. <loc>http://www.example.com/archive</loc>
44. </url>
45. <url>
46. <loc>http://www.example.com/community</loc>
47. </url>
48. <url>
49. <loc>http://forums.example.com/</loc>
50. </url>
51. </urlset>

Render the sitemap using a maximum depth of 1.

1. echo $this->navigation()
2. ->sitemap()
3. ->setFormatOutput(true)
4. ->setMaxDepth(1);

1. <?xml version="1.0" encoding="UTF-8"?>
2. <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
3. <url>
4. <loc>http://www.example.com/</loc>
5. </url>
6. <url>
7. <loc>http://www.example.com/products</loc>
8. </url>
9. <url>
10. <loc>http://www.example.com/products/server</loc>
11. </url>
12. <url>
13. <loc>http://www.example.com/products/studio</loc>
14. </url>
15. <url>
16. <loc>http://www.example.com/company/about</loc>
17. </url>
18. <url>
19. <loc>http://www.example.com/company/about/investors</loc>
20. </url>
21. <url>
22. <loc>http://www.example.com/company/news</loc>
23. </url>
24. <url>
25. <loc>http://www.example.com/community</loc>
26. </url>
27. <url>
28. <loc>http://www.example.com/community/account</loc>
29. </url>
30. <url>
31. <loc>http://forums.example.com/</loc>
32. </url>
33. </urlset>

> Note: UTF-8 encoding used by default
> By default, Zend Framework uses UTF-8 as its default encoding, and, specific to this case, Zend_View does as well. Character encoding can be set differently on the view object itself using the setEncoding() method (or the encoding instantiation parameter). However, since Zend_View_Interface does not define accessors for encoding, it's possible that if you are using a custom view implementation with the Dojo view helper, you will not have a getEncoding() method, which is what the view helper uses internally for determining the character set in which to encode.
> If you do not want to utilize UTF-8 in such a situation, you will need to implement a getEncoding() method in your custom view implementation.

# Navigation Helper

The Navigation helper is a proxy helper that relays calls to other navigational helpers. It can be considered an entry point to all navigation-related view tasks. The aforementioned navigational helpers are in the namespace Zend_View_Helper_Navigation, and would thus require the path `Zend/View/Helper/Navigation` to be added as a helper path to the view. With the proxy helper residing in the Zend_View_Helper namespace, it will always be available, without the need to add any helper paths to the view.

The Navigation helper finds other helpers that implement the Zend_View_Helper_Navigation_Helper interface, which means custom view helpers can also be proxied. This would, however, require that the custom helper path is added to the view.

When proxying to other helpers, the Navigation helper can inject its container, ACL/role, and translator. This means that you won't have to explicitly set all three in all navigational helpers, nor resort to injecting by means of Zend_Registry or static methods.

- findHelper() finds the given helper, verifies that it is a navigational helper, and injects container, ACL/role and translator.

- `{get|set}InjectContainer()` gets/sets a flag indicating whether the container should be injected to proxied helpers. Default is `TRUE`.

- `{get|set}InjectAcl()` gets/sets a flag indicating whether the ACL/role should be injected to proxied helpers. Default is `TRUE`.

- `{get|set}InjectTranslator()` gets/sets a flag indicating whether the translator should be injected to proxied helpers. Default is `TRUE`.

- `{get|set}DefaultProxy()` gets/sets the default proxy. Default is `'menu'`.

- render() proxies to the render method of the default proxy.

# TinySrc Helper

# Overview

» tinysrc.net provides an API for automatic scaling and image format conversion for use with mobile devices. The API is quite simple: you simply create a standard HTML image tag, but append your image URL to a URL on the tinysrc.net domain:

1. <img src="http://i.tinysrc.net/http://yourdomain.com/images/foo.jpg" />

Their service then sizes the image appropriately for the device requesting it.

You can control a number of aspects regarding image display, including:

- Image dimensions. You may specify a width and optional height. These dimensions can be in absolute pixels, or use one of the adaptive mechanisms tinysrc.net offers. One is subtractive; prepending a dimension with a minus ("-") indicates that the image should fill the maximum physical dimensions, minus the value given in pixels. The other is percentage based; prepending a dimension with an "x" tells the service to size that dimension by that percentage -- e.g., "x20" indicates "20%".

- Image format. By default, tinysrc.net autodiscovers the format. Internally, it supports only JPEG or PNG, and autoconverts GIF to PNG. You can specifically request that it should convert an image to either PNG or JPEG, however.

The TinySrc view helper provides functionality around the tinysrc.net API, and gives you the ability to:

- selectively enable or disable whether it returns just the tinysrc.net URL or a fully-populated HTML img tag (enabled by default);

- specify default values for image format as well as width and height;

- specify a default value for the base URL used (uses the BaseUrl view helper by default);

- override the default options on a per-image basis, via passed in options.

# Quick Start

The most basic usage is simply to pass the path to an image, relative to your document root or base URL, to create the appropriate image tag:

1. <?php echo $this->tinySrc('/images/foo.png'); ?>

You may specify default values for the base URL, conversion format, dimensions, and whether or not to create an img tag by default:

1. <?php $this->tinySrc()
2. ->setBaseUrl('http://example.com/foo/')
3. ->setCreateTag(false) // disable tag creation
4. ->setDefaultFormat('png') // convert images to PNG
5. ->setDefaultDimensions('-5', 'x20'); // width should be 5 less than screen width;
6. // height should be 20% of total screen height
7. ?>

Finally, you can also pass in values as an array of options, passed as the second parameter:

1. <?php echo $this->tinySrc('/images/foo.png', array (
2. 'format' => 'jpg', // convert to JPEG
3. 'width' => 'x50', // 1/2 screen width
4. ); ?>

# Configuration Options

# TinySrc Helper Options

The following options may be passed to the $options (second) argument of the helper.

base_url

  The base URL, including scheme, host, and optionally port and/or path; this value will be prepended to the image path provided in the first argument. By default, this uses the BaseUrl and ServerUrl view helpers to determine the value.

create_tag

  A boolean value indicating whether or not the helper should return an HTML img tag, or simply the tinysrc.net URL. By default, this flag is enabled.

format

  Should be one of the values "png" or "jpeg". If specified, this value will be used to indicate the image conversion format. If not specified, the default format will be used, or the format will be auto-determined based on the image itself.

width

  This should be either `null`, or an integer (optionally prefixed by "x" or "-"). If specified, this value will be used to determine the converted image width. If null, neither a width nor a height value will be used. If not specified, the default dimensions will be used.

height

  This should be either `null`, or an integer (optionally prefixed by "x" or "-"). If specified, this value will be used to determine the converted image height. If null, no height value will be used. If not specified, the default height will be used.

Any other options provided will be used as attributes to the HTML img tag (if created).

# Available Methods

tinySrc ( $image = null, array $options = array() )

  Called with no arguments, returns the helper instance. This is useful for configuring the helper.

  If the $image argument is provided, it will either create and return the tinysrc.net URL for the image, or an image tag containing that URL as the source, depending on the status of the "create tag" flag (either the default value, or the value passed via $options).

  See the configuration section for details on the $options array.

setBaseUrl ( $url )

  Use this method to manually specify the base URL to prepend to the $image argument of the tinySrc() method.

getBaseUrl

  Retrieve the base URL for prepending to image URLs. By default, autodiscovers this from the BaseUrl and ServerUrl view helpers.

setDefaultFormat ( $format = null )

  Specifiy the default image conversion format. If none provided, the value is cleared. Otherwise, expects either "png" or "jpeg".

setDefaultDimensions ( $width = null, $height = null )

  Set the default dimensions for image conversion. If no $width is specified, an empty value is provided for all dimensions (setting the height requires a width as well). Passing no value for the height will set only a width. Dimensions should be specified as either pixel dimensions, or:

  - A pixel value, preceded by a "-" sign. This will indicate the width should take the entire screen size, minus the number of pixels specified.

  - A percentage of the total screen dimensions, expressed as "x" followed by the percentage: "x20" is equivalent to 20%.

setCreateTag ( $flag )

  Indicate whether the tinySrc() method should create an HTML image tag. If boolean `false`, only a tinysrc.net URL will be returned.

createTag

  Returns the status of the "create tag" flag.

# Examples

Example #53 Returning only a tinysrc.net URL

You may want to return only a tinysrc.net URL. To do this, you have two options: make this the default behavior, or specify in your $options not to create a tag.

1. // Specifying default behavior:
2. $this->tinySrc()->setCreateTag(false);
3. echo $this->tinySrc('image.jpg');
5. // Per-image:
6. echo $this->tinySrc('image.jpg', array ('create_tag' => false));

# Translate Helper

Often web sites are available in several languages. To translate the content of a site you should simply use Zend_Translate and to integrate Zend_Translate within your view you should use the Translate View Helper.

In all following examples we are using the simple Array Translation Adapter. Of course you can also use any instance of Zend_Translate and also any subclasses of Zend_Translate_Adapter. There are several ways to initiate the Translate View Helper:

- Registered, through a previously registered instance in Zend_Registry

- Afterwards, through the fluent interface

- Directly, through initiating the class

A registered instance of Zend_Translate is the preferred usage for this helper. You can also select the locale to be used simply before you add the adapter to the registry.

> Note: We are speaking of locales instead of languages because a language also may contain a region. For example English is spoken in different dialects. There may be a translation for British and one for American English. Therefore, we say "locale" instead of "language."

Example #54 Registered instance

To use a registered instance just create an instance of Zend_Translate or Zend_Translate_Adapter and register it within Zend_Registry using Zend_Translate as its key.

1. // our example adapter
2. $adapter = new Zend_Translate(
3. array (
4. 'adapter' => 'array',
5. 'content' => array ('simple' => 'einfach'),
6. 'locale' => 'de'
7. )
8. );
9. Zend_Registry::set('Zend_Translate', $adapter);
11. // within your view
12. echo $this->translate('simple');
13. // this returns 'einfach'

If you are more familiar with the fluent interface, then you can also create an instance within your view and initiate the helper afterwards.

Example #55 Within the view

To use the fluent interface, create an instance of Zend_Translate or Zend_Translate_Adapter, call the helper without a parameter, and call the setTranslator() method.

1. // within your view
2. $adapter = new Zend_Translate(
3. array (
4. 'adapter' => 'array',
5. 'content' => array ('simple' => 'einfach'),
6. 'locale' => 'de'
7. )
8. );
9. $this->translate()->setTranslator($adapter)->translate('simple');
10. // this returns 'einfach'

If you are using the helper without Zend_View then you can also use it directly.

Example #56 Direct usage

1. // our example adapter
2. $adapter = new Zend_Translate(
3. array (
4. 'adapter' => 'array',
5. 'content' => array ('simple' => 'einfach'),
6. 'locale' => 'de'
7. )
8. );
10. // initiate the adapter
11. $translate = new Zend_View_Helper_Translate($adapter);
12. print $translate->translate('simple'); // this returns 'einfach'

You would use this way if you are not working with Zend_View and need to create translated output.

As already seen, the translate() method is used to return the translation. Just call it with the needed messageid of your translation adapter. But it can also replace parameters within the translation string. Therefore, it accepts variable parameters in two ways: either as a list of parameters, or as an array of parameters. As examples:

Example #57 Single parameter

To use a single parameter just add it to the method.

1. // within your view
2. $date = "Monday";
3. $this->translate("Today is %1\$s", $date);
4. // could return 'Heute ist Monday'

> Note: Keep in mind that if you are using parameters which are also text, you may also need to translate these parameters.

Example #58 List of parameters

Or use a list of parameters and add it to the method.

1. // within your view
2. $date = "Monday";
3. $month = "April";
4. $time = "11:20:55";
5. $this->translate("Today is %1\$s in %2\$s. Actual time: %3\$s",
6. $date,
7. $month,
8. $time);
9. // Could return 'Heute ist Monday in April. Aktuelle Zeit: 11:20:55'

Example #59 Array of parameters

Or use an array of parameters and add it to the method.

1. // within your view
2. $date = array ("Monday", "April", "11:20:55");
3. $this->translate("Today is %1\$s in %2\$s. Actual time: %3\$s", $date);
4. // Could return 'Heute ist Monday in April. Aktuelle Zeit: 11:20:55'

Sometimes it is necessary to change the locale of the translation. This can be done either dynamically per translation or statically for all following translations. And you can use it with both a parameter list and an array of parameters. In both cases the locale must be given as the last single parameter.

Example #60 Change locale dynamically

1. // within your view
2. $date = array ("Monday", "April", "11:20:55");
3. $this->translate("Today is %1\$s in %2\$s. Actual time: %3\$s", $date, 'it');

This example returns the Italian translation for the messageid. But it will only be used once. The next translation will use the locale from the adapter. Normally you will set the desired locale within the translation adapter before you add it to the registry. But you can also set the locale from within the helper:

Example #61 Change locale statically

1. // within your view
2. $date = array ("Monday", "April", "11:20:55");
3. $this->translate()->setLocale('it');
4. $this->translate("Today is %1\$s in %2\$s. Actual time: %3\$s", $date);

The above example sets 'it' as the new default locale which will be used for all further translations.

Of course there is also a getLocale() method to get the currently set locale.

Example #62 Get the currently set locale

1. // within your view
2. $date = array ("Monday", "April", "11:20:55");
4. // returns 'de' as set default locale from our above examples
5. $this->translate()->getLocale();
7. $this->translate()->setLocale('it');
8. $this->translate("Today is %1\$s in %2\$s. Actual time: %3\$s", $date);
10. // returns 'it' as new set default locale
11. $this->translate()->getLocale();

# UserAgent View Helper

# Overview

This view helper provides the ability to inject and later retrieve a Zend_Http_UserAgent instance for use in branching display logic based on device capabilities.

# Quick Start

In most cases, you can simply retrieve the User-Agent and related device by calling the helper. If the UserAgent was configured in the bootstrap, that instance will be injected already in the helper; otherwise, it will instantiate one for you.

1. <?php if ($this->userAgent()->getDevice()->hasFlash()): ?>
2. <object ...></object>
3. <?php endif ?>

If you initialize the UserAgent object manually, you can still inject it into the helper, in one of two ways.

1. // Pull the helper from the view, and inject:
2. $helper = $view->getHelper('userAgent');
3. $helper->setUserAgent($userAgent);
5. // Pass the UserAgent to the helper:
6. $view->userAgent($userAgent);

# Available Methods

userAgent ( Zend_Http_UserAgent $userAgent = null )

  Use this method to set or retrieve the UserAgent instance. Passing an instance will set it; passing no arguments will retrieve it. If no previous instance has been registered, one will be lazy-loaded using defaults.

setUserAgent ( Zend_Http_UserAgent $userAgent )

  If you have an instance of the helper -- for instance, by calling the view object's getHelper() method -- you may use this method to set the UserAgent instance.

getUserAgent

  Retrieves the UserAgent instance; if none is registered, it will lazy-load one using default values.

# Helper Paths

As with view scripts, your controller can specify a stack of paths for Zend_View to search for helper classes. By default, Zend_View looks in "Zend/View/Helper/*" for helper classes. You can tell Zend_View to look in other locations using the setHelperPath() and addHelperPath() methods. Additionally, you can indicate a class prefix to use for helpers in the path provided, to allow namespacing your helper classes. By default, if no class prefix is provided, 'Zend_View_Helper_' is assumed.

1. $view = new Zend_View();
3. // Set path to /path/to/more/helpers, with prefix 'My_View_Helper'
4. $view->setHelperPath('/path/to/more/helpers', 'My_View_Helper');

In fact, you can "stack" paths using the addHelperPath() method. As you add paths to the stack, Zend_View will look at the most-recently-added path for the requested helper class. This allows you to add to (or even override) the initial distribution of helpers with your own custom helpers.

1. $view = new Zend_View();
2. // Add /path/to/some/helpers with class prefix 'My_View_Helper'
3. $view->addHelperPath('/path/to/some/helpers', 'My_View_Helper');
4. // Add /other/path/to/helpers with class prefix 'Your_View_Helper'
5. $view->addHelperPath('/other/path/to/helpers', 'Your_View_Helper');
7. // now when you call $this->helperName(), Zend_View will look first for
8. // "/path/to/some/helpers/HelperName" using class name
9. // "Your_View_Helper_HelperName", then for
10. // "/other/path/to/helpers/HelperName.php" using class name
11. // "My_View_Helper_HelperName", and finally for
12. // "Zend/View/Helper/HelperName.php" using class name
13. // "Zend_View_Helper_HelperName".

# Writing Custom Helpers

Writing custom helpers is easy; just follow these rules:

- While not strictly necessary, we recommend either implementing Zend_View_Helper_Interface or extending Zend_View_Helper_Abstract when creating your helpers. Introduced in 1.6.0, these simply define a setView() method; however, in upcoming releases, we plan to implement a strategy pattern that will simplify much of the naming schema detailed below. Building off these now will help you future-proof your code.

- The class name must, at the very minimum, end with the helper name itself, using MixedCaps. E.g., if you were writing a helper called "specialPurpose", the class name would minimally need to be "SpecialPurpose". You may, and should, give the class name a prefix, and it is recommended that you use 'View_Helper' as part of that prefix: "My_View_Helper_SpecialPurpose". (You will need to pass in the prefix, with or without the trailing underscore, to addHelperPath() or setHelperPath()).

- The class must have a public method that matches the helper name; this is the method that will be called when your template calls "$this->specialPurpose()". In our "specialPurpose" helper example, the required method declaration would be "public function specialPurpose()".

- In general, the class should not echo or print or otherwise generate output. Instead, it should return values to be printed or echoed. The returned values should be escaped appropriately.

- The class must be in a file named after the helper class. Again using our "specialPurpose" helper example, the file has to be named "SpecialPurpose.php".

Place the helper class file somewhere in your helper path stack, and Zend_View will automatically load, instantiate, persist, and execute it for you.

Here is an example of our SpecialPurpose helper code:

1. class My_View_Helper_SpecialPurpose extends Zend_View_Helper_Abstract
2. {
3. protected $_count = 0;
4. public function specialPurpose()
5. {
6. $this->_count++;
7. $output = "I have seen 'The Jerk' {$this->_count} time(s).";
8. return htmlspecialchars ($output);
9. }
10. }

Then in a view script, you can call the SpecialPurpose helper as many times as you like; it will be instantiated once, and then it persists for the life of that Zend_View instance.

1. // remember, in a view script, $this refers to the Zend_View instance.
2. echo $this->specialPurpose();
3. echo $this->specialPurpose();
4. echo $this->specialPurpose();

The output would look something like this:

1. I have seen 'The Jerk' 1 time (s).
2. I have seen 'The Jerk' 2 time (s).
3. I have seen 'The Jerk' 3 time (s).

Sometimes you will need access to the calling Zend_View object -- for instance, if you need to use the registered encoding, or want to render another view script as part of your helper. To get access to the view object, your helper class should have a setView($view) method, like the following:

1. class My_View_Helper_ScriptPath
2. {
3. public $view;
5. public function setView(Zend_View_Interface $view)
6. {
7. $this->view = $view;
8. }
10. public function scriptPath($script)
11. {
12. return $this->view->getScriptPath($script);
13. }
14. }

If your helper class has a setView() method, it will be called when the helper class is first instantiated, and passed the current view object. It is up to you to persist the object in your class, as well as determine how it should be accessed.

If you are extending Zend_View_Helper_Abstract, you do not need to define this method, as it is defined for you.

# Registering Concrete Helpers

Sometimes it is convenient to instantiate a view helper, and then register it with the view. As of version 1.10.0, this is now possible using the registerHelper() method, which expects two arguments: the helper object, and the name by which it will be registered.

1. $helper = new My_Helper_Foo();
2. // ...do some configuration or dependency injection...
4. $view->registerHelper($helper, 'foo');

If the helper has a setView() method, the view object will call this and inject itself into the helper on registration.

> Note: Helper name should match a method
> The second argument to registerHelper() is the name of the helper. A corresponding method name should exist in the helper; otherwise, Zend_View will call a non-existent method when invoking the helper, raising a fatal PHP error.

View Scripts | Zend_View Programmer's Reference Guide | Zend_View_Abstract