Помощники видов
Часто бывает так, что в скриптах вида необходимо повторно выполнять
определенный набор функций; например, формирование даты,
генерация элементов формы, отображение ссылок. Вы можете использовать
помощников для выполнения этих действий.
Помощник представляет собой просто класс. Скажем, нам нужен помощник
'fooBar'. По умолчанию имя класса помощника начинается с
'Zend_View_Helper_' (вы можете указать другой префикс при
установке путей к помощникам видов), последней частью имени класа
является имя помощника. Все слова этой части должны писаться слитно,
первые буквы слов - в верхнем регистре (TitleCapped); таким образом мы
получаем имя класа Zend_View_Helper_FooBar. Класс должен
содержать как минимум один метод, названный по имени помощника в формате
camelCase: fooBar() .
Note: Следите за регистром
Имена помощников всегда должны быть в стиле camelCased, т.е. они
никогда не начинаются с символа в верхнем регистре. Имя класса
имеет стиль MixedCase (т.е. начинается с символа в верхнем регистре),
но реально выполняемый метод должен быть в стиле camelCase.
Note: Используемый по умолчанию путь к помощникам
Используемый по умолчанию путь к помощникам всегда указывает на
помощники Zend Framework-а, т.е. 'Zend/View/Helper/'. Даже если вы
вызываете setHelperPath() для перезаписи существующих
путей, этот путь всегда будет использоваться для обеспечения работы
помощников, входящих в поставку Zend Framework-а
Для того, чтобы использовать помощника в своем скрипте вида, вызывайте
его, используя $this->имяПомощника().
В этом случае Zend_View загрузит класс
Zend_View_Helper_ИмяПомощника , создаст его экземпляр и
вызовет его метод имяПомощника() . Экземпляр объекта
сохраняется в экземпляре Zend_View и будет повторно
использоваться им во всех будущих вызовах
$this->имяПомощника().
Начальный набор помощников
Zend_View поставляется с начальным набором помощников,
большинство из которых связано с генерацией элементов форм и
автоматически экранирует весь вывод. Кроме этого, есть помощники для
создания HTML-списков, URL-ов на основе маршрутов, и объявления
переменных. В настоящее время в поставляемый набор входят:
declareVars(): В основном предназначен для
использования вместе с strictVars() . Этот
помощник может использоваться для объявления переменных
шаблонов, которые не обязательно присутствуют в объекте
вида, и для установки значений по умолчанию.
Массивы, переданные методу в качестве аргуметов, будут
использованы для установки значений по умолчанию; иначе, если
переменная не существует, то ее значением будет пустая строка.
fieldset($name, $content, $attribs): Создает
XHTML-элемент fieldset (набор полей). Если массив
$attribs содержит в ключ 'legend', то это значение
используется для элемента legend . Элемент
fieldset будет содержать в себе значение
параметра $content, переданного помощнику.
form($name, $attribs, $content): Генерирует
XHTML-элемент form (форма). Все элементы массива
$attribs и добавляются как аттрибуты тега
form . Если параметр $content передан и
не имеет значение false, то это содержимое добавляется между
открывающим и закрывающим тегами формы. Если же
$content имеет булево значение false (значение по
умолчанию), то будет сгенерирован только открывающий тег формы.
formButton($name, $value, $attribs) : Создает элемент
<button /> .
-
formCheckbox($name, $value, $attribs, $options) :
Создает элемент <input type="checkbox" />
(флажок опций).
По умолчанию, если не был передан параметры $value
и $options, то значение '1' соотвествует
выбранному состоянию, '0' - не выбранному. Если был передан
параметр $value, но
не передан $options, то значение
$value соотвествует выбранному состоянию.
$options должен быть массивом. Если это
индексный массив, то первое значение соответствует
выбранному состоянию, второе - не выбранному состоянию,
все остальные значения игнорируются. Вы можете также
передавать массив с ключами 'checked' и 'unChecked'.
Если параметр $options был передан, и $value
соответствует значению в выбранном состоянии, то элемент
будет помечен как выбранный. Вы можете также помечать
элемент как выбранный или не выбранный путем передачи
значения булевого типа для атрибута 'checked'.
Наверное, лучше всего проиллюстрировать это примерами:
// '1' и '0' в качестве значений для выбранного/ не выбранного состояний
// флажок не выбран
echo $this-> formCheckbox('foo');
// '1' и '0' в качестве значений для выбранного/ не выбранного состояний
// флажок выбран
echo $this-> formCheckbox('foo', null, array('checked' => true));
// 'bar' и '0' в качестве значений для выбранного/ не выбранного состояний
// флажок не выбран
echo $this-> formCheckbox('foo', 'bar');
// 'bar' и '0' в качестве значений для выбранного/ не выбранного состояний
// флажок выбран
echo $this-> formCheckbox('foo', 'bar', array('checked' => true));
// 'bar' и 'baz' в качестве значений для выбранного/ не выбранного состояний
// флажок не выбран
echo $this-> formCheckbox('foo', null, null, array('bar', 'baz');
// 'bar' и 'baz' в качестве значений для выбранного/ не выбранного состояний
// флажок не выбран
echo $this-> formCheckbox('foo', null, null, array(
'checked' => 'bar',
'unChecked' => 'baz'
));
// 'bar' и 'baz' в качестве значений для выбранного/ не выбранного состояний
// флажок выбран
echo $this-> formCheckbox('foo', 'bar', null, array('bar', 'baz');
echo $this-> formCheckbox('foo',
null,
array('checked' => true),
// 'bar' и 'baz' в качестве значений для выбранного/ не выбранного состояний
// флажок не выбран
echo $this-> formCheckbox('foo', 'baz', null, array('bar', 'baz');
echo $this-> formCheckbox('foo',
null,
array('checked' => false),
Во всех случаях разметка предваряется скрытым элементом
<input type="hidden" />
со значением для не выбранного состояния. Таким образом,
и в том случае, если флажок опций не был выбран, вы будете
получать корректное значение, возвращаемое вашей форме.
-
formErrors($errors, $options): Генерирует
ненумерованный список XHTML для вывода сообщений об ошибках.
$errors должен быть строкой или массивом строк.
$options должен заключать в себе все аттрибуты,
которые вы хотите поместить в открывающий тег списка.
Вы можете указать альтернативный открывающий, закрывающий и
разделяющий код путем вызова нескольких методов данного
помощника:
setElementStart($string) ; по умолчанию
используется
'<ul class="errors"%s"><li>', где %s
заменяется аттрибутами, указанными в
$options.
setElementSeparator($string) ; по
умолчанию используется '</li><li>'.
setElementEnd($string) ; по умолчанию
используется '</li></ul>'.
formFile($name, $attribs) : Создает
элемент <input type="file" /> .
formHidden($name, $value, $attribs) : Создает
элемент <input type="hidden" /> .
formLabel($name, $value, $attribs): Создает элемент
<label>, устанавливая значение аттрибута for
равным значению $name, и содержимое элемента равным
значению $value. Если в $attribs был
передан disable , то ничего не будет возвращено.
formMultiCheckbox($name, $value, $attribs, $options,
$listsep):
Создает список флажков опций. $options должен
быть ассоциативным массивом, который может быть произвольной
глубины. $value может быть скалярным значением или
массивом выбранных значений, которые соответствуют ключам в
массиве $options. $listsep по
умолчанию является переносом строки в HTML ("<br />"). По
умолчанию этот элемент интерпретируется как массив - все флажки
опций имеют одно и то же имя и передаются как массив.
formPassword($name, $value, $attribs) : Создает
элемент <input type="password" /> .
formRadio($name, $value, $attribs, $options) : Создает
последовательность элементов <input type="radio" />
(переключатель опций). В массиве $options ключ
является значением переключателя, значение является содержимым
элемента label к переключателю. Переключатель опций
со значением $value будет предварительно выбранным.
formReset($name, $value, $attribs) : Создает
элемент <input type="reset" /> .
formSelect($name, $value, $attribs, $options) :
Создает блок <select>...</select> ,
с опциями <option> , соотвествующими
элементам массива $options. В массиве
$options ключ является значением опции,
значение - текстом опции. Опция со значением
$value будет предварительно выбранной.
formSubmit($name, $value, $attribs) : Создает
элемент <input type="submit" /> .
formText($name, $value, $attribs) : Создает
элемент <input type="text" /> .
formTextarea($name, $value, $attribs) : Создает
блок <textarea>...</textarea> .
url($urlOptions, $name, $reset): Создает строку
URL, основываясь на машруте с именем $name.
$urlOptions должен быть ассоциативным массивом пар
ключ-значение для использования в данном маршруте.
htmlList($items, $ordered, $attribs, $escape):
Генерирует маркированный или нумерованный список на основе
$items. Если $items является
многомерным массивом, то будут построены вложенные списки. Если
$escape установлен в true (значение по умолчанию),
то все пункты будут экранированы с использованием механизма,
зарегистрированного в объекте вида. Передавайте значение false,
если хотите использовать разметку в своих списках. Если
$ordered установлен в false (значение по
умолчанию), то генерируется маркированный список, иначе -
нумерованный.
Использовать их в скрипте вида очень просто, вот пример.
Обратите внимание, все, что вам нужно - это вызывать их,
помощники будут загружаться и инстанцироваться автоматически, по
мере необходимости.
// в скрипте вида $this ссылается на экземпляр Zend_View
//
// предположим, вы уже имеете последовательность опций $countries
// в виде массива ('us' => 'United States', 'il' =>
// 'Israel', 'de' => 'Germany')
?>
<form action="action.php" method="post">
<p><label>Your Email:
<?php echo $this-> formText('email', 'you@example.com', array('size' => 32)) ?>
</label></p>
<p><label>Your Country:
<?php echo $this-> formSelect('country', 'us', null, $this-> countries) ?>
</label></p>
<p><label>Would you like to opt in?
<?php echo $this-> formCheckbox('opt_in', 'yes', null, array('yes', 'no')) ?>
</label></p>
</form>
Результирующие выходные данные этого скрипта вида будут выглядеть
примерно следующим образом:
<form action="action.php" method="post">
<p><label>Your Email:
<input type="text" name="email" value="you@example.com" size="32" />
</label></p>
<p><label>Your Country:
<select name="country">
<option value="us" selected="selected">United States</option>
<option value="il">Israel</option>
<option value="de">Germany</option>
</select>
</label></p>
<p><label>Would you like to opt in?
<input type="hidden" name="opt_in" value="no" />
<input type="checkbox" name="opt_in" value="yes" checked="checked" />
</label></p>
</form>
Помощник Action
Помощник видов Action позволяет скриптам вида
вызывать действия из контроллеров, при этом будет
возвращаться результат из объекта ответа. Он может использоваться
в том случае, когда какое-то действие генерирует
повторно используемое содержимое или содержимое для "виджетов".
Действия, которые производят внутренний переход
(_forward() ) или перенаправление на другую страницу,
считаются недопустимыми и будут возвращать пустую строку.
API помощника Action аналогичен тому, который
использует большинство MVC-компонент при вызове действий:
action($action,
$controller, $module = null, array $params = array()) .
Параметры $action и $controller
являются обязательными; если не был указан модуль, то используется
модуль по умолчанию.
Example #1 Использование помощника Action
Допустим, вы имеете контроллер
CommentController с методом действия
listAction() , который желаете вызывать
с тем, чтобы получать список комментариев для текущего запроса:
<div id="sidebar right">
<div class="item">
<?php echo $this-> action('list',
'comment',
null,
array('count' => 10)); ?>
</div>
</div>
Cycle Helper
The Cycle helper is used to alternate a set of values.
Example #2 Cycle Helper Basic Usage
To add elements to cycle just specify them in constructor
or use assign(array $data) function
<?php foreach ($this->books as $book):?>
<tr style="background-color:<?php echo $this->cycle(array("#F0F0F0",
"#FFFFFF"))
->next()?>">
<td><?php echo $this->escape($book['author']) ?></td>
</tr>
<?php endforeach;?>
// Moving in backwards order and assign function
$this->cycle()->assign(array("#F0F0F0","#FFFFFF"));
$this->cycle()->prev();
?>
<tr style="background-color:'#F0F0F0'">
<td>First</td>
</tr>
<tr style="background-color:'#FFFFFF'">
<td>Second</td>
</tr>
Example #3 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.
<?php foreach ($this->books as $book):?>
<tr style="background-color:<?php echo $this->cycle(array("#F0F0F0",
"#FFFFFF"))
->next()?>">
<td><?php echo $this->cycle(array(1,2,3),'number')->next()?></td>
<td><?php echo $this->escape($book['author'])?></td>
</tr>
<?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 #4 Basic Usage of Partials
Basic usage of partials is to render a template fragment in its own
view scope. Consider the following partial script:
<?php // partial.phtml ?>
<ul>
<li>From: <?php echo $this-> escape($this-> from) ?></li>
<li>Subject: <?php echo $this-> escape($this-> subject) ?></li>
</ul>
You would then call it from your view script using the following:
<?php echo $this-> partial('partial.phtml', array(
'from' => 'Team Framework',
'subject' => 'view partials')); ?>
<ul>
<li>From: Team Framework</li>
<li>Subject: view partials</li>
</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:
// Tell partial to pass objects as 'model' variable
$view->partial()->setObjectKey('model');
// Tell partial to pass objects from partialLoop as 'model' variable
// in final partial view script:
$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 #5 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:
<?php // partialLoop.phtml ?>
<dt><?php echo $this-> key ?></dt>
<dd><?php echo $this-> value ?></dd>
And the following "model":
array('key' => 'Mammal', 'value' => 'Camel'),
array('key' => 'Bird', 'value' => 'Penguin'),
array('key' => 'Reptile', 'value' => 'Asp'),
array('key' => 'Fish', 'value' => 'Flounder'),
);
In your view script, you could then invoke the
PartialLoop helper:
<dl>
<?php echo $this-> partialLoop('partialLoop.phtml', $model) ?>
</dl>
<dl>
<dt>Mammal</dt>
<dd>Camel</dd>
<dt>Bird</dt>
<dd>Penguin</dd>
<dt>Reptile</dt>
<dd>Asp</dd>
<dt>Fish</dt>
<dd>Flounder</dd>
</dl>
Example #6 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:
<?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 #7 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.
<?php $this->placeholder('foo')->set("Some text for later") ?>
<?php
echo $this-> placeholder('foo');
// outputs "Some text for later"
?>
Example #8 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.
<!-- first view script -->
<?php $this->placeholder('foo')->exchangeArray($this->data) ?>
<!-- later view script -->
<?php
$this->placeholder('foo')->setPrefix("<ul>\n <li>")
->setSeparator("</li><li>\n")
->setIndent(4)
->setPostfix("</li></ul>\n");
?>
<?php
echo $this-> placeholder('foo');
// outputs as unordered list with pretty indentation
?>
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.
<?php $this->placeholder('foo')->bar = $this->data ?>
<?php echo $this-> placeholder('foo')-> bar ?>
<?php
$foo = $this->placeholder('foo');
?>
Example #9 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.
<!-- Default capture: append -->
<?php $this->placeholder('foo')->captureStart();
foreach ($this->data as $datum): ?>
<div class="foo">
<h2><?php echo $datum-> title ?></h2>
<p><?php echo $datum-> content ?></p>
</div>
<?php endforeach; ?>
<?php $this->placeholder('foo')->captureEnd() ?>
<?php echo $this-> placeholder('foo') ?>
<?php $this->placeholder('foo')->captureStart('SET', 'data');
foreach ($this->data as $datum): ?>
<div class="foo">
<h2><?php echo $datum-> title ?></h2>
<p><?php echo $datum-> content ?></p>
</div>
<?php endforeach; ?>
<?php $this->placeholder('foo')->captureEnd() ?>
<?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
Валидные HTML- и XHTML-документы должны включать в себя декларацию
DOCTYPE . Написание этих деклараций сложно для
запоминания, кроме того, от выбранного типа документа зависит то, как
должны выводиться элементы в вашем документе (например, экранирование
через CDATA в элементах <script> и
<style> ).
Помощник Doctype позволяет указать один из следующих
типов:
XHTML11
XHTML1_STRICT
XHTML1_TRANSITIONAL
XHTML1_FRAMESET
XHTML_BASIC1
HTML4_STRICT
HTML4_LOOSE
HTML4_FRAMESET
HTML5
Вы можете также определить любой другой тип, если он является
синтаксически корректным.
Помощник Doctype является частной реализацией
помощника
Placeholder.
Example #10 Использование помощника Doctype
Вы можете указать декларацию DOCTYPE в любой момент времени. Но
помощники, использующие эту декларацию при формированиии вывода,
увидят ее только после того, как она была определена.
Поэтому лучше всего указывать ее в вашем файле загрузки:
$doctypeHelper = new Zend_View_Helper_Doctype();
$doctypeHelper->doctype('XHTML1_STRICT');
И затем выводить ее в самом начале вашего скрипта вида:
<?php echo $this-> doctype() ?>
Example #11 Извлечение DOCTYPE
Если нужно узнать тип документа, то вы можете сделать
это путем вызова метода getDoctype() объекта,
возвращаемого при вызове помощника.
$doctype = $view->doctype()->getDoctype();
Часто требуется только узнать, соответствует ли декларация языку
XHTML или нет. В этом случае метода isXhtml() будет
достаточно:
if ($view->doctype()->isXhtml()) {
// сделать что-то
}
Помощник HeadLink
HTML-элемент <link> все чаще используется для
создания связей с различными ресурсами - таблицами стилей,
лентами новостей, пиктограммами (favicon), обратными ссылками (trackback)
и многим другим.
Помощник HeadLink предоставляет простой интерфейс
для создания и агрегирования этих элементов с целью последующего
извлечения и вывода в вашем скрипте макета (layout script).
Помощник HeadLink имеет специальные методы для добавления
таблиц стилей в его стек:
appendStylesheet($href, $media,
$conditionalStylesheet, $extras)
offsetSetStylesheet($index, $href, $media,
$conditionalStylesheet, $extras)
prependStylesheet($href, $media,
$conditionalStylesheet, $extras)
setStylesheet($href, $media,
$conditionalStylesheet, $extras)
По умолчанию аргумент $media имеет значение 'screen',
но через него могут передаваться и другие допустимые значения атрибута
media. $conditionalStylesheet может быть либо
строкой, либо иметь булево значение false, он используется
для определения того, требуется ли использовать специальные
комментарии для предотвращения загрузки данной таблицы стилей на
определенных платформах.
$extras является массивом дополнительных атрибутов,
которые вы хотите добавить в элемент.
Помощник HeadLink также имеет специальные методы
для добавления альтернативных связей в его стек:
appendAlternate($href, $type,
$title, $extras)
offsetSetAlternate($index, $href, $type,
$title, $extras)
prependAlternate($href, $type,
$title, $extras)
setAlternate($href, $type,
$title, $extras)
Метод headLink() позволяет указывать все
атрибуты, необходимые для элемента <link> ,
он также позволяет указывать место размещения -
новый элемент либо замещает все остальные элементы, либо добавляется в
начало/конец стека.
Помощник HeadLink является частной реализацией
помощника
Placeholder.
Example #12 Использование помощника HeadLink
Вы можете указывать headLink в любой момент времени.
Глобальные ссылки обычно указываются в скрипте макета,
а специальные (для отдельных страниц) - в скриптах вида.
В вашем скрипте макета, в разделе <head>, вы "выводите"
помощника, при этом будут выведены ссылки, которые вы добавили
ранее.
<?php // установка ссылок в скрипте вида:
$this->headLink()->appendStylesheet('/styles/basic.css')
-> headLink(array('rel' => 'favicon',
'href' => '/img/favicon.ico'),
'PREPEND')
->prependStylesheet('/styles/moz.css',
'screen',
true,
array('id' => 'my_stylesheet'));
?>
<?php // вывод ссылок: ?>
<?php echo $this-> headLink() ?>
Помощник HeadScript Helper
HTML-элемент <script> используется для добавления
скриптового кода, исполняемого на клиентской стороне, как
непосредственно в документ, так и через ссылки на удаленные ресурсы,
содержащие этот код. Помощник HeadScript позволяет
использовать оба способа включения.
Помощник HeadScript поддерживает следующие методы для
установки и добавления скриптов:
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())
В методах *File() через параметр $src
указывается местоположение скрипта, который требуется загрузить; обычно
оно указывется в виде URL или пути к нему.
В методах *Script() через параметр $script
передается скриптовый код, который требуется включить в
элемент <script> .
Note: Установка условных комментариев
HeadScript поддерживает включение тега в условные
комментарии с тем, чтобы скрыть его от определенных
браузеров. Для того, чтобы добавить условные теги,
передавайте условие через параметр
$attrs в вызове метода, как показано в примере:
Example #14 Скрипты с условными комментариями
// добавление скриптов
$this->headScript()->appendFile(
'/js/prototype.js',
'text/javascript',
array('conditional' => 'lt IE 7')
);
HeadScript также позволяет "захватывать" вывод скриптов;
это может быть полезным при создании скриптов
программным способом. Пример использования этой возможности будут
показан ниже.
Для быстрого добавления скриптовых элементов Вы можете использовать
метод headScript() , сигнатура этого метода -
headScript($mode = 'FILE', $spec, $placement = 'APPEND') .
Параметр $mode может иметь значение 'FILE' или 'SCRIPT',
в зависимости от того, ссылаетесь ли вы на уже существующий скрипт или
передаете код для влючения в элемент
<script> . $spec содержит либо путь к
файлу, к которому нужно добавить ссылку, либо сам скриптовый код.
$placement должен иметь одно из следующих значений:
'APPEND', 'PREPEND' или 'SET'.
HeadScript перегружает методы append() ,
offsetSet() , prepend() и set()
с целью принудительного использования специальных методов, перечисленных
выше. Внутри себя помощник сохраняет каждый элемент в виде маркера
stdClass , который затем преобразовывается в строку через
метод itemToString() . Это позволяет производить проверку
элементов в стеке и при необходимости модифицировать их, просто
извлекая объект и изменяя его.
Помощник HeadScript является частной реализацией
помощника
Placeholder.
Note: Используйте InlineScript для скриптов в теле документа
Для добавления скриптов внутри HTML-элемента body
должен использоваться
родственный помощник InlineScript.
Помещение скриптов в конец документа является хорошей практикой
для повышения скорости отдачи страницы, особенно если используются
сторонние скрипты-аналитики.
Note: Установка произвольных атрибутов по умолчанию отключена
По умолчанию HeadScript будет генерировать только
атрибуты, соответствующие спецификации W3C.
В список этих атрибутов входят 'type', 'charset', 'defer',
'language' и 'src'. Однако некоторые JavaScript фреймворки,
а в особенности » Dojo,
используют специальные атрибуты в целях изменения поведения. Вы
можете разрешить использование таких атрибутов, воспользовавшись
методом setAllowArbitraryAttributes() :
$this->headScript()->setAllowArbitraryAttributes(true);
Example #15 Использование помощника HeadScript
Вы можете указывать скрипты для добавления в документ в любой момент
времени. Как было указано ранее, это могут быть как ссылки на
файлы со скриптами, так и сами скрипты.
// добавление скриптов
$this->headScript()->appendFile('/js/prototype.js')
->appendScript($onloadScript);
Порядок следования часто важен в скриптах, интерпретируемых на
стороне клиента - например, нужно быть уверенным в том, что
библиотеки загружаются в порядке, обусловленном
зависимостями между ними. В этом случае используйте специальные
методы методы для добавления в начало, конец, и по определенному
смещению:
// Размещение скриптов в определенном порядке
// Добавление по определенному смещению
$this->headScript()->offsetSetFile(100, '/js/myfuncs.js');
// Используем эффекты из библиотеки script.aculo.us
// (будет добавлена с использованием следующего смещения, 101)
$this->headScript()->appendFile('/js/scriptaculous.js');
// Но скрипт prototype всегда должен загружаться первым:
$this->headScript()->prependFile('/js/prototype.js');
Когда все будет готово для размещения скриптов в макете, просто
"выводите" помощника:
<?php echo $this-> headScript() ?>
Example #16 Составление скриптов с использованием помощника HeadScript
Иногда нужно генерировать скрипты программым способом.
Хотя вы можете использовать конкатенацию строк, синтаксис heredoc
и т.п., часто бывает легче создать скрипт с включением PHP-тегов.
HeadScript позволяет делать это, захватывая
вывод в стек:
<?php $this->headScript()->captureStart() ?>
var action = '<?php echo $this->baseUrl ?>';
$('foo_form').action = action;
<?php $this->headScript()->captureEnd() ?>
Используются следующие допущения:
Скрипт будет добавлен в конец стека. Если требуется
переопределить содержимое стека или добавить скрипт в
конец стека, то передавайте соответственно
'SET' или 'PREPEND' в качестве первого аргумента
captureStart() .
По умолчанию предполагается, что MIME-тип скрипта -
'text/javascript'. Если требуется указать другой тип
скрипта, то передавайте его в качестве второго аргумента
captureStart() .
Если вы хотите указать какие-либо дополнительные аргументы
для тега <script> , то передавайте их
в массиве в качестве третьего аргумента
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 #17 Headstyle With Conditional Comments
// adding scripts
$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 #18 HeadStyle Helper Basic Usage
You may specify a new style tag at any time:
// adding styles
$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:
// Putting styles in order
// place at a particular offset:
$this->headStyle()->offsetSetStyle(100, $customStyles);
// place at end:
$this->headStyle()->appendStyle($finalStyles);
// place at beginning
$this->headStyle()->prependStyle($firstStyles);
When you're finally ready to output all style declarations in your
layout script, simply echo the helper:
<?php echo $this-> headStyle() ?>
Example #19 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:
<?php $this->headStyle()->captureStart() ?>
body {
background-color: <?php echo $this-> bgColor ?>;
}
<?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 #20 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.
// setting the controller and action name as title segments:
$request = Zend_Controller_Front::getInstance()->getRequest();
$this->headTitle($request->getActionName())
->headTitle($request->getControllerName());
// setting the site in the title; possibly in the layout script:
$this->headTitle('Zend Framework');
// setting a separator string for segments:
$this->headTitle()->setSeparator(' / ');
When you're finally ready to render the title in your layout
script, simply echo the helper:
<!-- renders <action> / <controller> / Zend Framework -->
<?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.
Embedding Flash in your page using the helper is pretty straight-forward.
The only required argument is the resource URI.
<?php echo $this-> htmlFlash('/path/to/flash.swf'); ?>
This outputs the following HTML:
<object data="/path/to/flash.swf"
type="application/x-shockwave-flash"
classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab">
</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 #22 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.
'/path/to/file.ext',
'mime/type',
'attr1' => 'aval1',
'attr2' => 'aval2'
),
'param1' => 'pval1',
'param2' => 'pval2'
),
'some content'
);
/*
This would output:
<object data="/path/to/file.ext" type="mime/type"
attr1="aval1" attr2="aval2">
<param name="param1" value="pval1" />
<param name="param2" value="pval2" />
some content
</object>
*/
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.
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:
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:
<?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.
// Boolean true as second argument enables layouts:
echo $this-> json($this-> data, true);
// Or boolean true as "keepLayouts" key:
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:
'enableJsonExprFinder' => true,
'keepLayouts' => true,
)) ?>
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:
// Boolean false as third argument disables internal JSON encoding of data
echo $this-> json($this-> data, false, false);
// Or boolean false as "encodeData" key:
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 #23 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.
$this-> navigation()-> addPage(array(
'type' => 'uri',
'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.
/*
* Navigation container (config/array)
* Each element in the array will be passed to
* Zend_Navigation_Page::factory() when constructing
* the navigation container below.
*/
'label' => 'Home',
'title' => 'Go Home',
'module' => 'default',
'controller' => 'index',
'action' => 'index',
'order' => -100 // make sure home is the first page
),
'label' => 'Special offer this week only!',
'module' => 'store',
'controller' => 'offer',
'action' => 'amazing',
'visible' => false // not visible
),
'label' => 'Products',
'module' => 'products',
'controller' => 'index',
'action' => 'index',
'label' => 'Foo Server',
'module' => 'products',
'controller' => 'server',
'action' => 'index',
'label' => 'FAQ',
'module' => 'products',
'controller' => 'server',
'action' => 'faq',
'canonical' => 'http://www.example.com/?page=faq',
'module' => 'products',
'controller' => 'server',
'action' => 'faq',
'params' => array('format' => 'xml')
)
)
),
'label' => 'Editions',
'module' => 'products',
'controller' => 'server',
'action' => 'editions'
),
'label' => 'System Requirements',
'module' => 'products',
'controller' => 'server',
'action' => 'requirements'
)
)
),
'label' => 'Foo Studio',
'module' => 'products',
'controller' => 'studio',
'action' => 'index',
'label' => 'Customer Stories',
'module' => 'products',
'controller' => 'studio',
'action' => 'customers'
),
'label' => 'Support',
'module' => 'prodcts',
'controller' => 'studio',
'action' => 'support'
)
)
)
)
),
'label' => 'Company',
'title' => 'About us',
'module' => 'company',
'controller' => 'about',
'action' => 'index',
'label' => 'Investor Relations',
'module' => 'company',
'controller' => 'about',
'action' => 'investors'
),
'label' => 'News',
'class' => 'rss', // class
'module' => 'company',
'controller' => 'news',
'action' => 'index',
'label' => 'Press Releases',
'module' => 'company',
'controller' => 'news',
'action' => 'press'
),
'label' => 'Archive',
'route' => 'archive', // route
'module' => 'company',
'controller' => 'news',
'action' => 'archive'
)
)
)
)
),
'label' => 'Community',
'module' => 'community',
'controller' => 'index',
'action' => 'index',
'label' => 'My Account',
'module' => 'community',
'controller' => 'account',
'action' => 'index',
'resource' => 'mvc:community.account' // resource
),
'label' => 'Forums',
'uri' => 'http://forums.example.com/',
'class' => 'external' // class
)
)
),
'label' => 'Administration',
'module' => 'admin',
'controller' => 'index',
'action' => 'index',
'resource' => 'mvc:admin', // resource
'label' => 'Write new article',
'module' => 'admin',
'controller' => 'post',
'aciton' => 'write'
)
)
)
);
// Create container from array
$container = new Zend_Navigation($pages);
// Store the container in the proxy helper:
$view->getHelper('navigation')->setContainer($container);
// ...or simply:
$view->navigation($container);
// ...or store it in the reigstry:
Zend_Registry::set('Zend_Navigation', $container);
In addition to the container above, the following setup is assumed:
// Setup router (default routes and 'archive' route):
$front = Zend_Controller_Front::getInstance();
$router = $front->getRouter();
$router->addDefaultRoutes();
$router->addRoute(
'archive',
new Zend_Controller_Router_Route(
'/archive/:year',
'module' => 'company',
'controller' => 'news',
'action' => 'archive',
'year' => (int ) date('Y') - 1
),
)
);
// Setup ACL:
$acl = new Zend_Acl();
$acl->addRole(new Zend_Acl_Role('member'));
$acl->addRole(new Zend_Acl_Role('admin'));
$acl->add(new Zend_Acl_Resource('mvc:admin'));
$acl->add(new Zend_Acl_Resource('mvc:community.account'));
$acl->allow('member', 'mvc:community.account');
$acl->allow('admin', null);
// Store ACL and role in the proxy helper:
$view->navigation()->setAcl($acl)->setRole('member');
// ...or set default ACL and role statically:
Zend_View_Helper_Navigation_HelperAbstract::setDefaultAcl($acl);
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
' > ' .
-
{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 #24 Rendering breadcrumbs
This example shows how to render breadcrumbs with default
settings.
In a view script or layout:
<?php echo $this-> navigation()-> breadcrumbs(); ?>
The two calls above take advantage of the magic __toString() method,
and are equivalent to:
<?php echo $this-> navigation()-> breadcrumbs()-> render(); ?>
Output:
<a href="/products">Products</a> > <a href="/products/server">Foo Server</a> > FAQ
Example #25 Specifying indentation
This example shows how to render breadcrumbs with initial
indentation.
Rendering with 8 spaces indentation:
<?php echo $this-> navigation()-> breadcrumbs()-> setIndent(8);?>
Output:
<a href="/products">Products</a> > <a href="/products/server">Foo Server</a> > FAQ
Example #26 Customize breadcrumbs output
This example shows how to customze breadcrumbs output by
specifying various options.
In a view script or layout:
<?php
->breadcrumbs()
->setLinkLast(true) // link last page
->setMaxDepth(1) // stop at level 1
->setSeparator(' ▶' . PHP_EOL); // cool separator with newline
?>
Output:
<a href="/products">Products</a> ▶
<a href="/products/server">Foo Server</a>
/////////////////////////////////////////////////////
Setting minimum depth required to render breadcrumbs:
<?php
$this->navigation()->breadcrumbs()->setMinDepth(10);
echo $this-> navigation()-> breadcrumbs();
?>
Output:
Nothing, because the deepest active page is not at level 10 or deeper.
Example #27 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.
$partial = ;
echo $this-> navigation()-> breadcrumbs()
-> setPartial(array('breadcrumbs.phtml', 'default'));
Contents of
application/modules/default/views/breadcrumbs.phtml :
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_Links::RENDER_ALTERNATE
-
Zend_View_Helper_Navigation_Links::RENDER_STYLESHEET
-
Zend_View_Helper_Navigation_Links::RENDER_START
-
Zend_View_Helper_Navigation_Links::RENDER_NEXT
-
Zend_View_Helper_Navigation_Links::RENDER_PREV
-
Zend_View_Helper_Navigation_Links::RENDER_CONTENTS
-
Zend_View_Helper_Navigation_Links::RENDER_INDEX
-
Zend_View_Helper_Navigation_Links::RENDER_GLOSSARY
-
Zend_View_Helper_Navigation_Links::RENDER_COPYRIGHT
-
Zend_View_Helper_Navigation_Links::RENDER_CHAPTER
-
Zend_View_Helper_Navigation_Links::RENDER_SECTION
-
Zend_View_Helper_Navigation_Links::RENDER_SUBSECTION
-
Zend_View_Helper_Navigation_Links::RENDER_APPENDIX
-
Zend_View_Helper_Navigation_Links::RENDER_HELP
-
Zend_View_Helper_Navigation_Links::RENDER_BOOKMARK
-
Zend_View_Helper_Navigation_Links::RENDER_CUSTOM
-
Zend_View_Helper_Navigation_Links::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 #28 Specify relations in pages
This example shows how to specify relations in pages.
$container = new Zend_Navigation (array(
'label' => 'Relations using strings',
'alternate' => 'http://www.example.org/'
),
'alternate' => 'http://www.example.net/'
)
),
'label' => 'Relations using arrays',
'label' => 'Example.org',
'uri' => 'http://www.example.org/'
)
)
),
'label' => 'Relations using configs',
'alternate' => new Zend_Config (array(
'label' => 'Example.org',
'uri' => 'http://www.example.org/'
))
)
),
'label' => 'Relations using pages instance',
'alternate' => Zend_Navigation_Page:: factory(array(
'label' => 'Example.org',
'uri' => 'http://www.example.org/'
))
)
)
));
Example #29 Default rendering of links
This example shows how to render a menu from a container
registered/found in the view helper.
In a view script or layout:
<?php echo $this-> view-> navigation()-> links(); ?>
Output:
<link rel="alternate" href="/products/server/faq/format/xml">
<link rel="start" href="/" title="Home">
<link rel="next" href="/products/server/editions" title="Editions">
<link rel="prev" href="/products/server" title="Foo Server">
<link rel="chapter" href="/products" title="Products">
<link rel="chapter" href="/company/about" title="Company">
<link rel="chapter" href="/community" title="Community">
<link rel="canonical" href="http://www.example.com/?page=server-faq">
<link rev="subsection" href="/products/server" title="Foo Server">
Example #30 Specify which relations to render
This example shows how to specify which relations to find
and render.
$helper->setRenderFlag(Zend_View_Helper_Navigation_Links::RENDER_START |
Zend_View_Helper_Navigation_Links::RENDER_NEXT |
Zend_View_Helper_Navigation_Links::RENDER_PREV);
Output:
<link rel="start" href="/" title="Home">
<link rel="next" href="/products/server/editions" title="Editions">
<link rel="prev" href="/products/server" title="Foo Server">
Render only native link types:
$helper->setRenderFlag(Zend_View_Helper_Navigation_Links::RENDER_ALL ^
Zend_View_Helper_Navigation_Links::RENDER_CUSTOM);
Output:
<link rel="alternate" href="/products/server/faq/format/xml">
<link rel="start" href="/" title="Home">
<link rel="next" href="/products/server/editions" title="Editions">
<link rel="prev" href="/products/server" title="Foo Server">
<link rel="chapter" href="/products" title="Products">
<link rel="chapter" href="/company/about" title="Company">
<link rel="chapter" href="/community" title="Community">
<link rev="subsection" href="/products/server" title="Foo Server">
Render all but chapter:
$helper->setRenderFlag(Zend_View_Helper_Navigation_Links::RENDER_ALL ^
Zend_View_Helper_Navigation_Links::RENDER_CHAPTER);
Output:
<link rel="alternate" href="/products/server/faq/format/xml">
<link rel="start" href="/" title="Home">
<link rel="next" href="/products/server/editions" title="Editions">
<link rel="prev" href="/products/server" title="Foo Server">
<link rel="canonical" href="http://www.example.com/?page=server-faq">
<link rev="subsection" href="/products/server" title="Foo Server">
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 #42 Rendering an XML sitemap
This example shows how to render an XML sitemap based
on the setup we did further up.
// In a view script or layout:
// format output
$this->navigation()
->sitemap()
->setFormatOutput(true); // default is false
// other possible methods:
// ->setUseXmlDeclaration(false); // default is true
// ->setServerUrl('http://my.otherhost.com');
// default is to detect automatically
// print sitemap
echo $this-> navigation()-> sitemap();
Notice how pages that are invisible or pages with
ACL roles incompatible with the view helper are filtered
out:
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>http://www.example.com/</loc>
</url>
<url>
<loc>http://www.example.com/products</loc>
</url>
<url>
<loc>http://www.example.com/products/server</loc>
</url>
<url>
<loc>http://www.example.com/products/server/faq</loc>
</url>
<url>
<loc>http://www.example.com/products/server/editions</loc>
</url>
<url>
<loc>http://www.example.com/products/server/requirements</loc>
</url>
<url>
<loc>http://www.example.com/products/studio</loc>
</url>
<url>
<loc>http://www.example.com/products/studio/customers</loc>
</url>
<url>
<loc>http://www.example.com/prodcts/studio/support</loc>
</url>
<url>
<loc>http://www.example.com/company/about</loc>
</url>
<url>
<loc>http://www.example.com/company/about/investors</loc>
</url>
<url>
<loc>http://www.example.com/company/news</loc>
</url>
<url>
<loc>http://www.example.com/company/news/press</loc>
</url>
<url>
<loc>http://www.example.com/archive</loc>
</url>
<url>
<loc>http://www.example.com/community</loc>
</url>
<url>
<loc>http://www.example.com/community/account</loc>
</url>
<url>
<loc>http://forums.example.com/</loc>
</url>
</urlset>
Render the sitemap using no ACL role (should filter out
/community/account):
->sitemap()
->setFormatOutput(true)
->setRole();
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>http://www.example.com/</loc>
</url>
<url>
<loc>http://www.example.com/products</loc>
</url>
<url>
<loc>http://www.example.com/products/server</loc>
</url>
<url>
<loc>http://www.example.com/products/server/faq</loc>
</url>
<url>
<loc>http://www.example.com/products/server/editions</loc>
</url>
<url>
<loc>http://www.example.com/products/server/requirements</loc>
</url>
<url>
<loc>http://www.example.com/products/studio</loc>
</url>
<url>
<loc>http://www.example.com/products/studio/customers</loc>
</url>
<url>
<loc>http://www.example.com/prodcts/studio/support</loc>
</url>
<url>
<loc>http://www.example.com/company/about</loc>
</url>
<url>
<loc>http://www.example.com/company/about/investors</loc>
</url>
<url>
<loc>http://www.example.com/company/news</loc>
</url>
<url>
<loc>http://www.example.com/company/news/press</loc>
</url>
<url>
<loc>http://www.example.com/archive</loc>
</url>
<url>
<loc>http://www.example.com/community</loc>
</url>
<url>
<loc>http://forums.example.com/</loc>
</url>
</urlset>
Render the sitemap using a maximum depth of 1.
->sitemap()
->setFormatOutput(true)
->setMaxDepth(1);
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>http://www.example.com/</loc>
</url>
<url>
<loc>http://www.example.com/products</loc>
</url>
<url>
<loc>http://www.example.com/products/server</loc>
</url>
<url>
<loc>http://www.example.com/products/studio</loc>
</url>
<url>
<loc>http://www.example.com/company/about</loc>
</url>
<url>
<loc>http://www.example.com/company/about/investors</loc>
</url>
<url>
<loc>http://www.example.com/company/news</loc>
</url>
<url>
<loc>http://www.example.com/community</loc>
</url>
<url>
<loc>http://www.example.com/community/account</loc>
</url>
<url>
<loc>http://forums.example.com/</loc>
</url>
</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.
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 #43 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.
// our example adapter
$adapter = new Zend_Translate(
'adapter' => 'array',
'content' => array('simple' => 'einfach'),
'locale' => 'de'
)
);
Zend_Registry::set('Zend_Translate', $adapter);
// within your view
echo $this-> translate('simple');
// 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 #44 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.
// within your view
$adapter = new Zend_Translate(
'adapter' => 'array',
'content' => array('simple' => 'einfach'),
'locale' => 'de'
)
);
$this->translate()->setTranslator($adapter)->translate('simple');
// this returns 'einfach'
If you are using the helper without Zend_View then you can
also use it directly.
// our example adapter
$adapter = new Zend_Translate(
'adapter' => 'array',
'content' => array('simple' => 'einfach'),
'locale' => 'de'
)
);
// initiate the adapter
$translate = new Zend_View_Helper_Translate($adapter);
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 #46 Single parameter
To use a single parameter just add it to the method.
// within your view
$date = "Monday";
$this->translate("Today is %1\$s", $date);
// 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 #47 List of parameters
Or use a list of parameters and add it to the method.
// within your view
$date = "Monday";
$month = "April";
$time = "11:20:55";
$this->translate("Today is %1\$s in %2\$s. Actual time: %3\$s",
$date,
$month,
$time);
// Could return 'Heute ist Monday in April. Aktuelle Zeit: 11:20:55'
Example #48 Array of parameters
Or use an array of parameters and add it to the method.
// within your view
$date = array("Monday", "April", "11:20:55");
$this->translate("Today is %1\$s in %2\$s. Actual time: %3\$s", $date);
// 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 #49 Change locale dynamically
// within your view
$date = array("Monday", "April", "11:20:55");
$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 #50 Change locale statically
// within your view
$date = array("Monday", "April", "11:20:55");
$this->translate()->setLocale('it');
$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 #51 Get the currently set locale
// within your view
$date = array("Monday", "April", "11:20:55");
// returns 'de' as set default locale from our above examples
$this->translate()->getLocale();
$this->translate()->setLocale('it');
$this->translate("Today is %1\$s in %2\$s. Actual time: %3\$s", $date);
// returns 'it' as new set default locale
$this->translate()->getLocale();
Пути к классам помощников
Как и для скриптов вида, ваш контроллер может задать
стек путей, в которых Zend_View должен искать
классы помощников. По умолчанию Zend_View
ищет классы помощников в Zend/View/Helper/* . Используя
методы setHelperPath() и addHelperPath() ,
вы можете укзать Zend_View, чтобы он искал классы
помощников в других местах. Кроме этого, вы можете указать префикс
класса, используемый для помощников, находящихся в данном пути;
префикс обеспечивает пространство имен. Если префикс не указан, то
по умолчанию используется 'Zend_View_Helper_'.
$view = new Zend_View();
// Устанавливает путь /path/to/more/helpers с префиксом 'My_View_Helper'
$view->setHelperPath('/path/to/more/helpers', 'My_View_Helper');
Вы можете "складывать" в стек пути, используя метод
addHelperPath() . Если вы добавили
пути в стек, то Zend_View будет искать запрошенный
класс помощника в этих путях, начиная с пути, добавленного
последним. Это дает возможность добавлять своих
помощников к начальному набору (или даже замещать имеющиеся).
$view = new Zend_View();
// Добавить /path/to/some/helpers с префиксом для классов 'My_View_Helper'
$view->addHelperPath('/path/to/some/helpers', 'My_View_Helper);
// Добавить /other/path/to/helpers с префиксом для классов 'Your_View_Helper'
$view->addHelperPath('/other/path/to/helpers', 'Your_View_Helper');
// теперь, когда вы вызываете $this->helperName(), Zend_View будет искать
// "/path/to/some/helpers/HelperName" с классом
// "Your_View_Helper_HelperName", затем "/other/path/to/helpers/HelperName.php"
// с классом "My_View_Helper_HelperName", и под конец
// "Zend/View/Helper/HelperName.php" с классом "Zend_View_Helper_HelperName".
Написание собственных помощников
Написать собственного помощника довольно легко, просто следуйте
этим правилам:
Хотя это и не является совершенно необходимым, мы рекомендуем
при создании своего помощника реализовывать интерфейс
Zend_View_Helper_Interface
или наследовать от класса Zend_View_Helper_Abstract.
Добавленные в версии 1.6.0, они определяют только метод
setView() , но в будущих релизах
мы планируем реализовать паттерн "стратегия", который
значительно упростит следование правилам по именованию,
изложенным ниже. Следование этой рекомендации сейчас
поможет в будущем избежать изменений в вашем коде.
Имя класса должно, как минимум, заканчиваться именем
помощника в стиле MixedCaps (СмешанныйРегистр). Т.е. если вы
пишете помощника с именем "specialPurpose", то наиболее короткое
имя класса должно быть "SpecialPurpose". Вы можете
(и должны) давать классам имена с префиксом, рекомендуется
использовать 'View_Helper' как часть этого префикса:
"My_View_Helper_SpecialPurpose". Вам нужно будет передать этот
префикс с или без завершающего знака подчеркивания методу
addHelperPath() или setHelperPath() .
Класс должен иметь открытый метод, имя которого
соответствует имени помощника. Это метод, который будет
вызываться, когда в вашем шаблоне производится вызов
$this->specialPurpose(). В нашем примере с
помощником "specialPurpose" объявление требуемого метода должно
быть public function specialPurpose() .
Обычно класс не должен выполнять вывод, вместо этого
он должен возвращать значение для вывода. Возвращаемое значение
должно быть экранировано должным образом.
Класс должен быть в файле, названном по имени класса.
Снова используя пример с помощником "specialPurpose", мы
должны дать файлу имя "SpecialPurpose.php".
Размещайте класс помощника где-либо в одном из находящихся в
стеке путей к помощникам, и Zend_View будет
автоматически загружать, инстанцировать, сохранять и выполнять его.
Вот пример кода нашего помощника SpecialPurpose :
class My_View_Helper_SpecialPurpose extends Zend_View_Helper_Abstract
{
protected $_count = 0;
public function specialPurpose()
{
$this->_count++;
$output = "I have seen 'The Jerk' {$this->_count} time(s).";
}
}
Далее в скрипте вида вы можете вызывать помощника
SpecialPurpose сколько угодно раз. Он будет
инстанцирован один раз, и существует, пока существует
экземпляр Zend_View.
// помните, что в скрипте вида $this ссылается на экземпляр Zend_View
echo $this-> specialPurpose();
echo $this-> specialPurpose();
echo $this-> specialPurpose();
Результат должен быть примерно следующим:
I have seen 'The Jerk' 1 time(s ).
I have seen 'The Jerk' 2 time(s ).
I have seen 'The Jerk' 3 time(s ).
Иногда бывает, что нужен доступ к объекту Zend_View -
например, нужно получить зарегистрированное значение кодировки
или произвести рендеринг другого скрипта вида как часть
действий, выполняемых вашим помощником. Для того, чтобы можно было
получить доступ к объекту вида, ваш класс помощника должен иметь
метод setView($view) , его пример показан ниже:
class My_View_Helper_ScriptPath
{
public $view;
public function setView(Zend_View_Interface $view)
{
$this->view = $view;
}
public function scriptPath($script)
{
return $this->view->getScriptPath($script);
}
}
Если ваш класс помощника имеет метод setView() , то он
будет вызываться при первом инстанцировании класса помощника и его
передаче текущему объекту вида. Реализация
сохранения объекта вида и доступа к нему в вашем классе помощника
остаются на ваше усмотрение.
Если вы наследуете своего помощника от
Zend_View_Helper_Abstract, то вам не нужно определять
этот метод, поскольку он уже определен в родительском классе.
|
|