Zend_View-Helpers.xml 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!-- EN-Revision: 24249 -->
  3. <!-- Reviewed: no -->
  4. <sect1 id="zend.view.helpers" xmlns:xi="http://www.w3.org/2001/XInclude">
  5. <title>Assistentes de Visualização</title>
  6. <para>
  7. Em seus scripts de visualização, frequentemente é necessário a execução de certas tarefas
  8. complexas repetidas vezes: p. ex.: formatar uma data, gerar um elemento de formulário, ou
  9. exibir links de acionamento. Você pode empregar classes assistentes para executar estas
  10. tarefas para você.
  11. </para>
  12. <para>
  13. A helper is simply a class. Let's say we want a helper named 'fooBar'.
  14. By default, the class is prefixed with 'Zend_View_Helper_'
  15. (you can specify a custom prefix when setting a helper path), and the
  16. last segment of the class name is the helper name; this segment should
  17. be TitleCapped; the full class name is then:
  18. <classname>Zend_View_Helper_FooBar</classname>. This class should contain at the
  19. minimum a single method, named after the helper, and camelCased:
  20. <methodname>fooBar()</methodname>.
  21. </para>
  22. <note>
  23. <title>Watch the Case</title>
  24. <para>
  25. Helper names are always camelCased, i.e., they never begin with an
  26. uppercase character. The class name itself is MixedCased, but the
  27. method that is actually executed is camelCased.
  28. </para>
  29. </note>
  30. <note>
  31. <title>Default Helper Path</title>
  32. <para>
  33. The default helper path always points to the Zend Framework view
  34. helpers, i.e., 'Zend/View/Helper/'. Even if you call
  35. <methodname>setHelperPath()</methodname> to overwrite the existing paths, this
  36. path will be set to ensure the default helpers work.
  37. </para>
  38. </note>
  39. <para>
  40. Para usar um assistente em seu script de visualização, chame-o usando
  41. <command>$this->helperName()</command>. Em segundo plano, <classname>Zend_View</classname>
  42. irá carregar a classe <classname>Zend_View_Helper_HelperName</classname>, instanciá-la e
  43. chamar seu método <methodname>helperName()</methodname>. O objeto criado é persistente
  44. dentro do escopo da instância <classname>Zend_View</classname>, e será reutilizado por todas
  45. as chamadas futuras a <command>$this->helperName()</command>.
  46. </para>
  47. <sect2 id="zend.view.helpers.initial">
  48. <title>Assistentes Padrão</title>
  49. <para>
  50. <classname>Zend_View</classname> vem com um conjunto padrão de assistentes, a maioria
  51. deles dedicados à geração de elementos de formulários e automaticamente escapar a saída
  52. apropriada. Além disso, existem assistentes para criar <acronym>URL</acronym>s baseadas
  53. em rotas e listas de <acronym>HTML</acronym>, bem como declarar variáveis. Os
  54. assistentes atualmente embarcados incluem:
  55. </para>
  56. <itemizedlist>
  57. <listitem>
  58. <para>
  59. <methodname>declareVars()</methodname>: Primarily for use when using
  60. <methodname>strictVars()</methodname>, this helper can be used to declare
  61. template variables that may or may not already be set in the
  62. view object, as well as to set default values. Arrays passed as
  63. arguments to the method will be used to set default values;
  64. otherwise, if the variable does not exist, it is set to an empty string.
  65. </para>
  66. </listitem>
  67. <listitem>
  68. <para>
  69. <methodname>fieldset($name, $content, $attribs)</methodname>: Creates an
  70. <acronym>XHTML</acronym> fieldset. If <varname>$attribs</varname> contains a
  71. 'legend' key, that value will be used for the fieldset legend. The
  72. fieldset will surround the <varname>$content</varname> as provided to
  73. the helper.
  74. </para>
  75. </listitem>
  76. <listitem>
  77. <para>
  78. <methodname>form($name, $attribs, $content)</methodname>: Generates an
  79. <acronym>XHTML</acronym> form. All <varname>$attribs</varname> are escaped and
  80. rendered as <acronym>XHTML</acronym> attributes of the form tag. If
  81. <varname>$content</varname> is present and not a boolean
  82. <constant>FALSE</constant>, then that content is rendered within the start and
  83. close form tags; if <varname>$content</varname> is a boolean
  84. <constant>FALSE</constant> (the default), only the opening form tag is
  85. generated.
  86. </para>
  87. </listitem>
  88. <listitem>
  89. <para>
  90. <methodname>formButton($name, $value, $attribs)</methodname>: Cria um elemento
  91. &lt;button /&gt;.
  92. </para>
  93. </listitem>
  94. <listitem>
  95. <para>
  96. <methodname>formCheckbox($name, $value, $attribs, $options)</methodname>:
  97. Cria um elemento &lt;input type="checkbox" /&gt;.
  98. </para>
  99. <para>
  100. By default, when no $value is provided and no $options are
  101. present, '0' is assumed to be the unchecked value, and '1'
  102. the checked value. If a $value is passed, but no $options
  103. are present, the checked value is assumed to be the value
  104. passed.
  105. </para>
  106. <para>
  107. $options should be an array. If the array is indexed, the
  108. first value is the checked value, and the second the
  109. unchecked value; all other values are ignored. You may also
  110. pass an associative array with the keys 'checked' and
  111. 'unChecked'.
  112. </para>
  113. <para>
  114. If $options has been passed, if $value matches the checked
  115. value, then the element will be marked as checked. You may
  116. also mark the element as checked or unchecked by passing a
  117. boolean value for the attribute 'checked'.
  118. </para>
  119. <para>
  120. The above is probably best summed up with some examples:
  121. </para>
  122. <programlisting language="php"><![CDATA[
  123. // '1' and '0' as checked/unchecked options; not checked
  124. echo $this->formCheckbox('foo');
  125. // '1' and '0' as checked/unchecked options; checked
  126. echo $this->formCheckbox('foo', null, array('checked' => true));
  127. // 'bar' and '0' as checked/unchecked options; not checked
  128. echo $this->formCheckbox('foo', 'bar');
  129. // 'bar' and '0' as checked/unchecked options; checked
  130. echo $this->formCheckbox('foo', 'bar', array('checked' => true));
  131. // 'bar' and 'baz' as checked/unchecked options; unchecked
  132. echo $this->formCheckbox('foo', null, null, array('bar', 'baz'));
  133. // 'bar' and 'baz' as checked/unchecked options; unchecked
  134. echo $this->formCheckbox('foo', null, null, array(
  135. 'checked' => 'bar',
  136. 'unChecked' => 'baz'
  137. ));
  138. // 'bar' and 'baz' as checked/unchecked options; checked
  139. echo $this->formCheckbox('foo', 'bar', null, array('bar', 'baz'));
  140. echo $this->formCheckbox('foo',
  141. null,
  142. array('checked' => true),
  143. array('bar', 'baz'));
  144. // 'bar' and 'baz' as checked/unchecked options; unchecked
  145. echo $this->formCheckbox('foo', 'baz', null, array('bar', 'baz'));
  146. echo $this->formCheckbox('foo',
  147. null,
  148. array('checked' => false),
  149. array('bar', 'baz'));
  150. ]]></programlisting>
  151. <para>
  152. In all cases, the markup prepends a hidden element with the
  153. unchecked value; this way, if the value is unchecked, you
  154. will still get a valid value returned to your form.
  155. </para>
  156. </listitem>
  157. <listitem>
  158. <para>
  159. <methodname>formErrors($errors, $options)</methodname>: Generates an
  160. <acronym>XHTML</acronym> unordered list to show errors.
  161. <varname>$errors</varname> should be a string or an array of strings;
  162. <varname>$options</varname> should be any attributes you want
  163. placed in the opening list tag.
  164. </para>
  165. <para>
  166. You can specify alternate opening, closing, and separator
  167. content when rendering the errors by calling several methods
  168. on the helper:
  169. </para>
  170. <itemizedlist>
  171. <listitem>
  172. <para>
  173. <methodname>setElementStart($string)</methodname>; default is
  174. '&lt;ul class="errors"%s"&gt;&lt;li&gt;', where %s
  175. is replaced with the attributes as specified in
  176. <varname>$options</varname>.
  177. </para>
  178. </listitem>
  179. <listitem>
  180. <para>
  181. <methodname>setElementSeparator($string)</methodname>; default
  182. is '&lt;/li&gt;&lt;li&gt;'.
  183. </para>
  184. </listitem>
  185. <listitem>
  186. <para>
  187. <methodname>setElementEnd($string)</methodname>; default is
  188. '&lt;/li&gt;&lt;/ul&gt;'.
  189. </para>
  190. </listitem>
  191. </itemizedlist>
  192. </listitem>
  193. <listitem>
  194. <para>
  195. <methodname>formFile($name, $attribs)</methodname>: Cria um elemento
  196. &lt;input type="file" /&gt;.
  197. </para>
  198. </listitem>
  199. <listitem>
  200. <para>
  201. <methodname>formHidden($name, $value, $attribs)</methodname>: Cria um elemento
  202. &lt;input type="hidden" /&gt;.
  203. </para>
  204. </listitem>
  205. <listitem>
  206. <para>
  207. <methodname>formLabel($name, $value, $attribs)</methodname>: Creates a
  208. &lt;label&gt; element, setting the <property>for</property> attribute to
  209. <varname>$name</varname>, and the actual label text to
  210. <varname>$value</varname>. If <emphasis>disable</emphasis> is passed in
  211. <property>attribs</property>, nothing will be returned.
  212. </para>
  213. </listitem>
  214. <listitem>
  215. <para>
  216. <methodname>formMultiCheckbox($name, $value, $attribs, $options,
  217. $listsep)</methodname>: Creates a list of checkboxes.
  218. <varname>$options</varname> should be an associative array, and may be
  219. arbitrarily deep. <varname>$value</varname> may be a single value or
  220. an array of selected values that match the keys in the
  221. <varname>$options</varname> array. <varname>$listsep</varname> is an
  222. <acronym>HTML</acronym> break ("&lt;br /&gt;") by default. By default, this
  223. element is treated as an array; all checkboxes share the same name, and are
  224. submitted as an array.
  225. </para>
  226. </listitem>
  227. <listitem>
  228. <para>
  229. <methodname>formPassword($name, $value, $attribs)</methodname>: Cria um elemento
  230. &lt;input type="password" /&gt;.
  231. </para>
  232. </listitem>
  233. <listitem>
  234. <para>
  235. <methodname>formRadio($name, $value, $attribs, $options)</methodname>: Cria uma
  236. série de elementos &lt;input type="radio" /&gt;, um para cada elemento em
  237. $options. Na matriz $options, a chave e seu valor estão associados ao valor do
  238. controle e seu rótulo, respectivamente. O conteúdo de $value será
  239. pré-selecionado.
  240. </para>
  241. </listitem>
  242. <listitem>
  243. <para>
  244. <methodname>formReset($name, $value, $attribs)</methodname>: Cria um elemento
  245. &lt;input type="reset" /&gt;.
  246. </para>
  247. </listitem>
  248. <listitem>
  249. <para>
  250. <methodname>formSelect($name, $value, $attribs, $options)</methodname>: Cria um
  251. bloco &lt;select&gt;...&lt;/select&gt;, com um &lt;option&gt; para cada elemento
  252. em $options. Na matriz $options, a chave e seu valor estão associados ao valor
  253. do controle e seu rótulo. O conteúdo de $value será pré-selecionado.
  254. </para>
  255. </listitem>
  256. <listitem>
  257. <para>
  258. <methodname>formSubmit($name, $value, $attribs)</methodname>: Cria um elemento
  259. &lt;input type="submit" /&gt;.
  260. </para>
  261. </listitem>
  262. <listitem>
  263. <para>
  264. <methodname>formText($name, $value, $attribs)</methodname>: Cria um elemento
  265. &lt;input type="text" /&gt;.
  266. </para>
  267. </listitem>
  268. <listitem>
  269. <para>
  270. <methodname>formTextarea($name, $value, $attribs)</methodname>: Cria um bloco
  271. &lt;textarea&gt;...&lt;/textarea&gt;.
  272. </para>
  273. </listitem>
  274. <listitem>
  275. <para>
  276. <methodname>url($urlOptions, $name, $reset)</methodname>: Creates a
  277. <acronym>URL</acronym> string based on a named route.
  278. <varname>$urlOptions</varname> should be an associative array of key/value pairs
  279. used by the particular route.
  280. </para>
  281. </listitem>
  282. <listitem>
  283. <para>
  284. <methodname>htmlList($items, $ordered, $attribs, $escape)</methodname>:
  285. generates unordered and ordered lists based on the <varname>$items</varname>
  286. passed to it. If <varname>$items</varname> is a multidimensional
  287. array, a nested list will be built. If the <varname>$escape</varname>
  288. flag is <constant>TRUE</constant> (default), individual items will be escaped
  289. using the view objects registered escaping mechanisms; pass a
  290. <constant>FALSE</constant> value if you want to allow markup in your lists.
  291. </para>
  292. </listitem>
  293. </itemizedlist>
  294. <para>
  295. Utilizar estes assistentes em seus scripts de visualização é muito fácil, aqui está um
  296. exemplo. Note que tudo que você necessita fazer é chamá-los; eles carregam e instanciam
  297. a sí próprios a medida que tornam-se necessários.
  298. </para>
  299. <programlisting language="php"><![CDATA[
  300. // dentro do seu script de visualização,
  301. // $this aponta para a instância de Zend_View.
  302. //
  303. // digamos que você já atribuiu uma série de valores a matriz
  304. // $countries = array('us' => 'United States', 'il' =>
  305. // 'Israel', 'de' => 'Germany').
  306. ?>
  307. <form action="action.php" method="post">
  308. <p><label>Your Email:
  309. <?php echo $this->formText('email', 'you@example.com', array('size' => 32)) ?>
  310. </label></p>
  311. <p><label>Your Country:
  312. <?php echo $this->formSelect('country', 'us', null, $this->countries) ?>
  313. </label></p>
  314. <p><label>Would you like to opt in?
  315. <?php echo $this->formCheckbox('opt_in', 'yes', null, array('yes', 'no')) ?>
  316. </label></p>
  317. </form>
  318. ]]></programlisting>
  319. <para>
  320. A saída resultante do script de visualização deverá se parecer com isto:
  321. </para>
  322. <programlisting language="php"><![CDATA[
  323. <form action="action.php" method="post">
  324. <p><label>Your Email:
  325. <input type="text" name="email" value="you@example.com" size="32" />
  326. </label></p>
  327. <p><label>Your Country:
  328. <select name="country">
  329. <option value="us" selected="selected">United States</option>
  330. <option value="il">Israel</option>
  331. <option value="de">Germany</option>
  332. </select>
  333. </label></p>
  334. <p><label>Would you like to opt in?
  335. <input type="hidden" name="opt_in" value="no" />
  336. <input type="checkbox" name="opt_in" value="yes" checked="checked" />
  337. </label></p>
  338. </form>
  339. ]]></programlisting>
  340. <xi:include href="Zend_View-Helpers-Action.xml" />
  341. <xi:include href="Zend_View-Helpers-BaseUrl.xml" />
  342. <xi:include href="Zend_View-Helpers-Currency.xml" />
  343. <xi:include href="Zend_View-Helpers-Cycle.xml" />
  344. <xi:include href="Zend_View-Helpers-Partial.xml" />
  345. <xi:include href="Zend_View-Helpers-Placeholder.xml" />
  346. <xi:include href="Zend_View-Helpers-Doctype.xml" />
  347. <xi:include href="Zend_View-Helpers-Gravatar.xml" />
  348. <xi:include href="Zend_View-Helpers-HeadLink.xml" />
  349. <xi:include href="Zend_View-Helpers-HeadMeta.xml" />
  350. <xi:include href="Zend_View-Helpers-HeadScript.xml" />
  351. <xi:include href="Zend_View-Helpers-HeadStyle.xml" />
  352. <xi:include href="Zend_View-Helpers-HeadTitle.xml" />
  353. <xi:include href="Zend_View-Helpers-HtmlObject.xml" />
  354. <xi:include href="Zend_View-Helpers-InlineScript.xml" />
  355. <xi:include href="Zend_View-Helpers-Json.xml" />
  356. <xi:include href="Zend_View-Helpers-Navigation.xml" />
  357. <xi:include href="Zend_View-Helpers-Translate.xml" />
  358. <xi:include href="Zend_View-Helpers-UserAgent.xml" />
  359. </sect2>
  360. <sect2 id="zend.view.helpers.paths">
  361. <title>Localizando os Assistentes</title>
  362. <para>
  363. Assim como os scripts de visualização, seu controlador pode especificar uma lista de
  364. caminhos onde o <classname>Zend_View</classname> deve procurar pelas classes
  365. assistentes. Por padrão, <classname>Zend_View</classname> procura pelas classes
  366. assistentes em "Zend/View/Helper/*". Você pode instruir o
  367. <classname>Zend_View</classname> a procurar em outros locais usando os métodos
  368. <methodname>setHelperPath()</methodname> e <methodname>addHelperPath()</methodname>.
  369. Além disso, você pode indicar um prefixo da classe a ser usado para os assistentes no
  370. caminho fornecido, permitindo o uso de namespaces em suas classes assistentes. Por
  371. padrão, se nenhum prefixo da classe for fornecido, 'Zend_View_Helper_' é assumido.
  372. </para>
  373. <programlisting language="php"><![CDATA[
  374. $view = new Zend_View();
  375. // Set path to /path/to/more/helpers, with prefix 'My_View_Helper'
  376. $view->setHelperPath('/path/to/more/helpers', 'My_View_Helper');
  377. ]]></programlisting>
  378. <para>
  379. De fato, você pode "empilhar" caminhos usando o método
  380. <methodname>addHelperPath()</methodname>. A medida que você adiciona caminhos à pilha,
  381. <classname>Zend_View</classname> procurará no caminho mais recentemente adicionado.
  382. Isto permite a você incrementar o conjunto original de assistentes (ou susbstituir) com
  383. os seus próprios personalizados.
  384. </para>
  385. <programlisting language="php"><![CDATA[
  386. $view = new Zend_View();
  387. // Add /path/to/some/helpers with class prefix 'My_View_Helper'
  388. $view->addHelperPath('/path/to/some/helpers', 'My_View_Helper');
  389. // Add /other/path/to/helpers with class prefix 'Your_View_Helper'
  390. $view->addHelperPath('/other/path/to/helpers', 'Your_View_Helper');
  391. // now when you call $this->helperName(), Zend_View will look first for
  392. // "/path/to/some/helpers/HelperName" using class name
  393. // "Your_View_Helper_HelperName", then for
  394. // "/other/path/to/helpers/HelperName.php" using class name
  395. // "My_View_Helper_HelperName", and finally for
  396. // "Zend/View/Helper/HelperName.php" using class name
  397. // "Zend_View_Helper_HelperName".
  398. ]]></programlisting>
  399. </sect2>
  400. <sect2 id="zend.view.helpers.custom">
  401. <title>Escrevendo Assistentes Personalizados</title>
  402. <para>
  403. Escrever assistentes personalizados é fácil; basta seguir estas regras:
  404. </para>
  405. <itemizedlist>
  406. <listitem>
  407. <para>
  408. While not strictly necessary, we recommend either implementing
  409. <classname>Zend_View_Helper_Interface</classname> or extending
  410. <classname>Zend_View_Helper_Abstract</classname> when creating your
  411. helpers. Introduced in 1.6.0, these simply define a
  412. <methodname>setView()</methodname> method; however, in upcoming releases, we
  413. plan to implement a strategy pattern that will simplify much of
  414. the naming schema detailed below. Building off these now will
  415. help you future-proof your code.
  416. </para>
  417. </listitem>
  418. <listitem>
  419. <para>
  420. The class name must, at the very minimum, end with the helper
  421. name itself, using MixedCaps. E.g., if you were writing a
  422. helper called "specialPurpose", the class name would minimally
  423. need to be "SpecialPurpose". You may, and should, give the class
  424. name a prefix, and it is recommended that you use 'View_Helper'
  425. as part of that prefix: "My_View_Helper_SpecialPurpose". (You
  426. will need to pass in the prefix, with or without the trailing
  427. underscore, to <methodname>addHelperPath()</methodname> or
  428. <methodname>setHelperPath()</methodname>).
  429. </para>
  430. </listitem>
  431. <listitem>
  432. <para>
  433. A classe deve ter um método público que coincida com o nome do assistente; este
  434. é o método que será chamado quando o seu template chamar
  435. "$this->specialPurpose()". Em nosso exemplo "specialPurpose", o método requerido
  436. deverá ser declarado como "public function specialPurpose()".
  437. </para>
  438. </listitem>
  439. <listitem>
  440. <para>
  441. Em geral, a classe não deve ecoar ou imprimir a saída gerada. Em lugar disso,
  442. ela deve retornar os valores a serem impressos. Os valores retornados deverão
  443. estar devidamente escapados.
  444. </para>
  445. </listitem>
  446. <listitem>
  447. <para>
  448. A classe deve estar em um arquivo chamado após a classe assistente. Voltando ao
  449. exemplo "specialPurpose", o arquivo recebeu o nome "SpecialPurpose.php".
  450. </para>
  451. </listitem>
  452. </itemizedlist>
  453. <para>
  454. Localize o arquivo com a classe assistente em algum dos caminhos armazenados na pilha,
  455. e o <classname>Zend_View</classname> automaticamente irá carregar, instanciar,
  456. persistir, e executar o código para você.
  457. </para>
  458. <para>
  459. Aqui está um exemplo do assistente <classname>SpecialPurpose</classname>:
  460. </para>
  461. <programlisting language="php"><![CDATA[
  462. class My_View_Helper_SpecialPurpose extends Zend_View_Helper_Abstract
  463. {
  464. protected $_count = 0;
  465. public function specialPurpose()
  466. {
  467. $this->_count++;
  468. $output = "I have seen 'The Jerk' {$this->_count} time(s).";
  469. return htmlspecialchars($output);
  470. }
  471. }
  472. ]]></programlisting>
  473. <para>
  474. Em um script de visualização, você pode chamar o assistente
  475. <classname>SpecialPurpose</classname> quantas vezes desejar; ele será instanciado apenas
  476. uma vez; e persistirá durante todo o tempo de vida da instância de
  477. <classname>Zend_View</classname>.
  478. </para>
  479. <programlisting language="php"><![CDATA[
  480. // remember, in a view script, $this refers to the Zend_View instance.
  481. echo $this->specialPurpose();
  482. echo $this->specialPurpose();
  483. echo $this->specialPurpose();
  484. ]]></programlisting>
  485. <para>
  486. A saída deverá se parecer com isto:
  487. </para>
  488. <programlisting language="php"><![CDATA[
  489. I have seen 'The Jerk' 1 time(s).
  490. I have seen 'The Jerk' 2 time(s).
  491. I have seen 'The Jerk' 3 time(s).
  492. ]]></programlisting>
  493. <para>
  494. Sometimes you will need access to the calling <classname>Zend_View</classname>
  495. object -- for instance, if you need to use the registered encoding,
  496. or want to render another view script as part of your helper. To get
  497. access to the view object, your helper class should have a
  498. <methodname>setView($view)</methodname> method, like the following:
  499. </para>
  500. <programlisting language="php"><![CDATA[
  501. class My_View_Helper_ScriptPath
  502. {
  503. public $view;
  504. public function setView(Zend_View_Interface $view)
  505. {
  506. $this->view = $view;
  507. }
  508. public function scriptPath($script)
  509. {
  510. return $this->view->getScriptPath($script);
  511. }
  512. }
  513. ]]></programlisting>
  514. <para>
  515. If your helper class has a <methodname>setView()</methodname> method, it will be
  516. called when the helper class is first instantiated, and passed the
  517. current view object. It is up to you to persist the object in your
  518. class, as well as determine how it should be accessed.
  519. </para>
  520. <para>
  521. If you are extending <classname>Zend_View_Helper_Abstract</classname>, you do
  522. not need to define this method, as it is defined for you.
  523. </para>
  524. </sect2>
  525. <sect2 id="zend.view.helpers.registering-concrete">
  526. <title>Registering Concrete Helpers</title>
  527. <para>
  528. Sometimes it is convenient to instantiate a view helper, and then register it with the
  529. view. As of version 1.10.0, this is now possible using the
  530. <methodname>registerHelper()</methodname> method, which expects two arguments: the
  531. helper object, and the name by which it will be registered.
  532. </para>
  533. <programlisting language="php"><![CDATA[
  534. $helper = new My_Helper_Foo();
  535. // ...do some configuration or dependency injection...
  536. $view->registerHelper($helper, 'foo');
  537. ]]></programlisting>
  538. <para>
  539. If the helper has a <methodname>setView()</methodname> method, the view object will call
  540. this and inject itself into the helper on registration.
  541. </para>
  542. <note>
  543. <title>Helper name should match a method</title>
  544. <para>
  545. The second argument to <methodname>registerHelper()</methodname> is the name of the
  546. helper. A corresponding method name should exist in the helper; otherwise,
  547. <classname>Zend_View</classname> will call a non-existent method when invoking the
  548. helper, raising a fatal <acronym>PHP</acronym> error.
  549. </para>
  550. </note>
  551. </sect2>
  552. </sect1>
  553. <!--
  554. vim:se ts=4 sw=4 et:
  555. -->