Zend_View-Scripts.xml 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!-- EN-Revision: 20799 -->
  3. <!-- Reviewed: no -->
  4. <sect1 id="zend.view.scripts">
  5. <title>Scripts de Visualização</title>
  6. <para>
  7. Uma vez que seu controlador tenha atribuido as variáveis e chamado o método
  8. <methodname>render()</methodname>, <classname>Zend_View</classname> incluirá o script de
  9. visualização requerido e o executará "dentro" do escopo da instância de
  10. <classname>Zend_View</classname>. Portanto, em seus scripts de visualização, as referências
  11. a $this apontarão para a própria instância de <classname>Zend_View</classname>.
  12. </para>
  13. <para>
  14. Variáveis atribuídas à visualização pelo controlador são referidas como propriedades de
  15. instância. Por exemplo, se o controlador atribuir a variável 'algumacoisa', você deve
  16. referir-se a ela como $this->algumacoisa em seu script de visualização. (Isto permite um
  17. rastreamento dos valores que foram atribuidos ao script, e que são internos ao mesmo).
  18. </para>
  19. <para>
  20. A fim de lembrar, aqui está um exemplo de script de visualização originado da introdução do
  21. <classname>Zend_View</classname>.
  22. </para>
  23. <programlisting language="php"><![CDATA[
  24. <?php if ($this->books): ?>
  25. <!-- Uma tabela contendo alguns livros. -->
  26. <table>
  27. <tr>
  28. <th>Autor</th>
  29. <th>Título</th>
  30. </tr>
  31. <?php foreach ($this->books as $key => $val): ?>
  32. <tr>
  33. <td><?php echo $this->escape($val['author']) ?></td>
  34. <td><?php echo $this->escape($val['title']) ?></td>
  35. </tr>
  36. <?php endforeach; ?>
  37. </table>
  38. <?php else: ?>
  39. <p>Não existem livros a serem exibidos.</p>
  40. <?php endif;?>
  41. ]]></programlisting>
  42. <sect2 id="zend.view.scripts.escaping">
  43. <title>Escapando a Saída</title>
  44. <para>
  45. Uma das tarefas mais importantes a ser executada por scripts de visualização é assegurar
  46. que a saída seja corretamente escapada; entre outras coisas, isto ajuda a evitar ataques
  47. do tipo site-cruzado. A menos que você esteja usando uma função, método, ou assistente
  48. que realize o escape, você sempre deverá escapar o conteúdo das variáveis antes de
  49. exibí-lo.
  50. </para>
  51. <para>
  52. <classname>Zend_View</classname> implementa um método chamado escape() que realiza
  53. corretamente o escape para você.
  54. </para>
  55. <programlisting language="php"><![CDATA[
  56. // maneira ruim:
  57. echo $this->variable;
  58. // maneira recomendada:
  59. echo $this->escape($this->variable);
  60. ]]></programlisting>
  61. <para>
  62. Por padrão, o método escape() usa a função htmlspecialchars() do <acronym>PHP</acronym>
  63. para fazer o escape. Mas, dependendo do seu ambiente, você pode desejar um comportamento
  64. diferente para o escape. Use o método setEscape() no nível do controlador para instruir
  65. o <classname>Zend_View</classname> sobre qual função de callback utilizar para fazer o
  66. escape.
  67. </para>
  68. <programlisting language="php"><![CDATA[
  69. // cria uma instância de Zend_View
  70. $view = new Zend_View();
  71. // instrui o uso de htmlentities como método de escape
  72. $view->setEscape('htmlentities');
  73. // ou instrui o uso de um método estático de classe
  74. $view->setEscape(array('SomeClass', 'methodName'));
  75. // ou mesmo um método de instância
  76. $obj = new SomeClass();
  77. $view->setEscape(array($obj, 'methodName'));
  78. // e renderiza a visualização
  79. echo $view->render(...);
  80. ]]></programlisting>
  81. <para>
  82. A função ou método de callback deverá tomar o valor a ser escapado como seu primeiro
  83. parâmetro, e os demais parâmetros deverão ser opcionais.
  84. </para>
  85. </sect2>
  86. <sect2 id="zend.view.scripts.templates">
  87. <title>Usando Sistemas de Template Alternativos</title>
  88. <para>
  89. Embora o <acronym>PHP</acronym> em si seja um poderoso sistema de template, muitos
  90. desenvolvedores sentiram que ele é muito potente ou complexo para seus designers de
  91. templates e acabam usando um motor de template alternativo.
  92. <classname>Zend_View</classname> fornece para isso dois mecanismos, o primeiro através
  93. de scripts de visualização, e o segundo implementando
  94. <classname>Zend_View_Interface</classname>.
  95. </para>
  96. <sect3 id="zend.view.scripts.templates.scripts">
  97. <title>Template Systems Using View Scripts</title>
  98. <para>
  99. A view script may be used to instantiate and manipulate a
  100. separate template object, such as a PHPLIB-style template. The
  101. view script for that kind of activity might look something like
  102. this:
  103. </para>
  104. <programlisting language="php"><![CDATA[
  105. include_once 'template.inc';
  106. $tpl = new Template();
  107. if ($this->books) {
  108. $tpl->setFile(array(
  109. "booklist" => "booklist.tpl",
  110. "eachbook" => "eachbook.tpl",
  111. ));
  112. foreach ($this->books as $key => $val) {
  113. $tpl->set_var('author', $this->escape($val['author']);
  114. $tpl->set_var('title', $this->escape($val['title']);
  115. $tpl->parse("books", "eachbook", true);
  116. }
  117. $tpl->pparse("output", "booklist");
  118. } else {
  119. $tpl->setFile("nobooks", "nobooks.tpl")
  120. $tpl->pparse("output", "nobooks");
  121. }
  122. ]]></programlisting>
  123. <para>
  124. Estes seriam os arquivos de template relacionados:
  125. </para>
  126. <programlisting language="html"><![CDATA[
  127. <!-- booklist.tpl -->
  128. <table>
  129. <tr>
  130. <th>Autor</th>
  131. <th>Título</th>
  132. </tr>
  133. {books}
  134. </table>
  135. <!-- eachbook.tpl -->
  136. <tr>
  137. <td>{author}</td>
  138. <td>{title}</td>
  139. </tr>
  140. <!-- nobooks.tpl -->
  141. <p>Não existem livros a serem exibidos.</p>
  142. ]]></programlisting>
  143. </sect3>
  144. <sect3 id="zend.view.scripts.templates.interface">
  145. <title>Template Systems Using Zend_View_Interface</title>
  146. <para>
  147. Some may find it easier to simply provide a
  148. <classname>Zend_View</classname>-compatible template engine.
  149. <classname>Zend_View_Interface</classname> defines the minimum interface needed for
  150. compatability:
  151. </para>
  152. <programlisting language="php"><![CDATA[
  153. /**
  154. * Return the actual template engine object
  155. */
  156. public function getEngine();
  157. /**
  158. * Set the path to view scripts/templates
  159. */
  160. public function setScriptPath($path);
  161. /**
  162. * Set a base path to all view resources
  163. */
  164. public function setBasePath($path, $prefix = 'Zend_View');
  165. /**
  166. * Add an additional base path to view resources
  167. */
  168. public function addBasePath($path, $prefix = 'Zend_View');
  169. /**
  170. * Retrieve the current script paths
  171. */
  172. public function getScriptPaths();
  173. /**
  174. * Overloading methods for assigning template variables as object
  175. * properties
  176. */
  177. public function __set($key, $value);
  178. public function __isset($key);
  179. public function __unset($key);
  180. /**
  181. * Manual assignment of template variables, or ability to assign
  182. * multiple variables en masse.
  183. */
  184. public function assign($spec, $value = null);
  185. /**
  186. * Unset all assigned template variables
  187. */
  188. public function clearVars();
  189. /**
  190. * Render the template named $name
  191. */
  192. public function render($name);
  193. ]]></programlisting>
  194. <para>
  195. Using this interface, it becomes relatively easy to wrap a
  196. third-party template engine as a <classname>Zend_View</classname>-compatible class.
  197. As an example, the following is one potential wrapper for Smarty:
  198. </para>
  199. <programlisting language="php"><![CDATA[
  200. class Zend_View_Smarty implements Zend_View_Interface
  201. {
  202. /**
  203. * Smarty object
  204. * @var Smarty
  205. */
  206. protected $_smarty;
  207. /**
  208. * Constructor
  209. *
  210. * @param string $tmplPath
  211. * @param array $extraParams
  212. * @return void
  213. */
  214. public function __construct($tmplPath = null, $extraParams = array())
  215. {
  216. $this->_smarty = new Smarty;
  217. if (null !== $tmplPath) {
  218. $this->setScriptPath($tmplPath);
  219. }
  220. foreach ($extraParams as $key => $value) {
  221. $this->_smarty->$key = $value;
  222. }
  223. }
  224. /**
  225. * Return the template engine object
  226. *
  227. * @return Smarty
  228. */
  229. public function getEngine()
  230. {
  231. return $this->_smarty;
  232. }
  233. /**
  234. * Set the path to the templates
  235. *
  236. * @param string $path The directory to set as the path.
  237. * @return void
  238. */
  239. public function setScriptPath($path)
  240. {
  241. if (is_readable($path)) {
  242. $this->_smarty->template_dir = $path;
  243. return;
  244. }
  245. throw new Exception('Invalid path provided');
  246. }
  247. /**
  248. * Retrieve the current template directory
  249. *
  250. * @return string
  251. */
  252. public function getScriptPaths()
  253. {
  254. return array($this->_smarty->template_dir);
  255. }
  256. /**
  257. * Alias for setScriptPath
  258. *
  259. * @param string $path
  260. * @param string $prefix Unused
  261. * @return void
  262. */
  263. public function setBasePath($path, $prefix = 'Zend_View')
  264. {
  265. return $this->setScriptPath($path);
  266. }
  267. /**
  268. * Alias for setScriptPath
  269. *
  270. * @param string $path
  271. * @param string $prefix Unused
  272. * @return void
  273. */
  274. public function addBasePath($path, $prefix = 'Zend_View')
  275. {
  276. return $this->setScriptPath($path);
  277. }
  278. /**
  279. * Assign a variable to the template
  280. *
  281. * @param string $key The variable name.
  282. * @param mixed $val The variable value.
  283. * @return void
  284. */
  285. public function __set($key, $val)
  286. {
  287. $this->_smarty->assign($key, $val);
  288. }
  289. /**
  290. * Allows testing with empty() and isset() to work
  291. *
  292. * @param string $key
  293. * @return boolean
  294. */
  295. public function __isset($key)
  296. {
  297. return (null !== $this->_smarty->get_template_vars($key));
  298. }
  299. /**
  300. * Allows unset() on object properties to work
  301. *
  302. * @param string $key
  303. * @return void
  304. */
  305. public function __unset($key)
  306. {
  307. $this->_smarty->clear_assign($key);
  308. }
  309. /**
  310. * Assign variables to the template
  311. *
  312. * Allows setting a specific key to the specified value, OR passing
  313. * an array of key => value pairs to set en masse.
  314. *
  315. * @see __set()
  316. * @param string|array $spec The assignment strategy to use (key or
  317. * array of key => value pairs)
  318. * @param mixed $value (Optional) If assigning a named variable,
  319. * use this as the value.
  320. * @return void
  321. */
  322. public function assign($spec, $value = null)
  323. {
  324. if (is_array($spec)) {
  325. $this->_smarty->assign($spec);
  326. return;
  327. }
  328. $this->_smarty->assign($spec, $value);
  329. }
  330. /**
  331. * Clear all assigned variables
  332. *
  333. * Clears all variables assigned to Zend_View either via
  334. * {@link assign()} or property overloading
  335. * ({@link __get()}/{@link __set()}).
  336. *
  337. * @return void
  338. */
  339. public function clearVars()
  340. {
  341. $this->_smarty->clear_all_assign();
  342. }
  343. /**
  344. * Processes a template and returns the output.
  345. *
  346. * @param string $name The template to process.
  347. * @return string The output.
  348. */
  349. public function render($name)
  350. {
  351. return $this->_smarty->fetch($name);
  352. }
  353. }
  354. ]]></programlisting>
  355. <para>
  356. In this example, you would instantiate the
  357. <classname>Zend_View_Smarty</classname> class instead of
  358. <classname>Zend_View</classname>, and then use it in roughly the same
  359. fashion as <classname>Zend_View</classname>:
  360. </para>
  361. <programlisting language="php"><![CDATA[
  362. //Example 1. In initView() of initializer.
  363. $view = new Zend_View_Smarty('/path/to/templates');
  364. $viewRenderer =
  365. Zend_Controller_Action_HelperBroker::getStaticHelper('ViewRenderer');
  366. $viewRenderer->setView($view)
  367. ->setViewBasePathSpec($view->_smarty->template_dir)
  368. ->setViewScriptPathSpec(':controller/:action.:suffix')
  369. ->setViewScriptPathNoControllerSpec(':action.:suffix')
  370. ->setViewSuffix('tpl');
  371. //Example 2. Usage in action controller remains the same...
  372. class FooController extends Zend_Controller_Action
  373. {
  374. public function barAction()
  375. {
  376. $this->view->book = 'Zend PHP 5 Certification Study Guide';
  377. $this->view->author = 'Davey Shafik and Ben Ramsey'
  378. }
  379. }
  380. //Example 3. Initializing view in action controller
  381. class FooController extends Zend_Controller_Action
  382. {
  383. public function init()
  384. {
  385. $this->view = new Zend_View_Smarty('/path/to/templates');
  386. $viewRenderer = $this->_helper->getHelper('viewRenderer');
  387. $viewRenderer->setView($this->view)
  388. ->setViewBasePathSpec($view->_smarty->template_dir)
  389. ->setViewScriptPathSpec(':controller/:action.:suffix')
  390. ->setViewScriptPathNoControllerSpec(':action.:suffix')
  391. ->setViewSuffix('tpl');
  392. }
  393. ]]></programlisting>
  394. </sect3>
  395. </sect2>
  396. </sect1>
  397. <!--
  398. vim:se ts=4 sw=4 et:
  399. -->