PageRenderTime 43ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/en/views/helpers.rst

https://github.com/RobsonKarls/docs
ReStructuredText | 317 lines | 236 code | 81 blank | 0 comment | 0 complexity | 4223c1dbf7e191ff89743a93d67811fa MD5 | raw file
  1. Helpers
  2. #######
  3. Helpers are the component-like classes for the presentation layer
  4. of your application. They contain presentational logic that is
  5. shared between many views, elements, or layouts. This chapter will
  6. show you how to create your own helpers, and outline the basic
  7. tasks CakePHPs core helpers can help you accomplish.
  8. Helpers are the component-like classes for the presentation layer
  9. of your application. They contain presentational logic that is
  10. shared between many views, elements, or layouts.
  11. CakePHP features a number of helpers that aid in view creation.
  12. They assist in creating well-formed markup (including forms), aid
  13. in formatting text, times and numbers, and can even speed up Ajax
  14. functionality. For more information on the helpers included in CakePHP,
  15. check out :doc:`/core-libraries/helpers`.
  16. .. _configuring-helpers:
  17. Using and Configuring Helpers
  18. =============================
  19. You configure helpers in CakePHP by making a controller aware of them. Each
  20. controller has a :php:attr:`~Controller::$helpers` property that lists the
  21. helpers to be made available in the view. To enable a helper in your view, add
  22. the name of the helper to the controller's ``$helpers`` array::
  23. <?php
  24. class BakeriesController extends AppController {
  25. public $helpers = array('Form', 'Html', 'Javascript', 'Time');
  26. }
  27. Adding helpers from plugins, uses the :term:`plugin syntax` used elsewhere in
  28. CakePHP::
  29. <?php
  30. class BakeriesController extends AppController {
  31. public $helpers = array('Blog.Comment');
  32. }
  33. You can also add helpers from within an action, so they will only
  34. be available to that action and not the other actions in the
  35. controller. This saves processing power for the other actions that
  36. do not use the helper as well as help keep the controller better
  37. organized::
  38. <?php
  39. class BakeriesController extends AppController {
  40. function bake {
  41. $this->helpers[] = 'Time';
  42. }
  43. function mix {
  44. // The Time helper is not loaded here and thus not available
  45. }
  46. }
  47. If you need to enable a helper for all controllers add the name of
  48. the helper to the ``$helpers`` array in ``/app/Controller/AppController.php`` (or
  49. create if not present). Remember to include the default Html and
  50. Form helpers::
  51. <?php
  52. class AppController extends Controller {
  53. public $helpers = array('Form', 'Html', 'Javascript', 'Time');
  54. }
  55. You can pass options to helpers. These options can be used to set
  56. attribute values or modify behavior of a helper::
  57. <?php
  58. class AwesomeHelper extends AppHelper {
  59. function __construct(View $view, $settings = array()) {
  60. parent::__construct($view, $settings);
  61. debug($options);
  62. }
  63. }
  64. class AwesomeController extends AppController {
  65. var $helpers = array('Awesome' => array('option1' => 'value1'));
  66. }
  67. One common setting to use is the ``className`` option, which allows you to
  68. create aliased helpers in your views. This feature is useful when you want to
  69. replace ``$this->Html`` or another common Helper reference with a custom
  70. implmentation::
  71. <?php
  72. class PostsController extends AppController {
  73. public $helpers = array(
  74. 'Html' => array(
  75. 'className' => 'MyHtml'
  76. )
  77. );
  78. }
  79. The above would *alias* ``MyHtmlHelper`` to ``$this->Html`` in your views.
  80. .. note::
  81. Aliasing a helper replaces that instance anywhere that helper is used,
  82. including inside other Helpers.
  83. Using helper settings allows you to declaritively configure your helpers. And
  84. keep configuration logic out of your controller actions. If you have
  85. configuration options that cannot be included as part of a class declaration,
  86. you can set those in your controller's beforeRender callback::
  87. <?php
  88. class PostsController extends AppController {
  89. function beforeRender() {
  90. parent::beforeRender();
  91. $this->helpers['CustomStuff'] = $this->_getCustomStuffSettings();
  92. }
  93. }
  94. Using Helpers
  95. =============
  96. Once you've configured which helpers you want to use in your controller,
  97. each helper is exposed as a public property in the view. For example, if you
  98. were using the :php:class:`HtmlHelper` you would be able to access it by
  99. doing the following::
  100. <?php
  101. echo $this->Html->css('styles');
  102. The above would call the ``css`` method on the HtmlHelper. You can
  103. access any loaded helper using ``$this->{$helperName}``. There may
  104. come a time where you need to dynamically load a helper from inside
  105. a view. You can use the view's :php:class:`HelperCollection` to
  106. do this::
  107. <?php
  108. $mediaHelper = $this->Helpers->load('Media', $mediaSettings);
  109. The HelperCollection is a :doc:`collection </core-libraries/collections>` and
  110. supports the collection API used elsewhere in CakePHP.
  111. Callback methods
  112. ================
  113. Helpers feature several callbacks that allow you to augment the
  114. view rendering process. See the :ref:`helper-api` and the
  115. :doc:`/core-libraries/collections` documentation for more information.
  116. Creating Helpers
  117. ================
  118. If a core helper (or one showcased on github or the Bakery)
  119. doesnt fit your needs, helpers are easy to create.
  120. Let's say we wanted to create a helper that could be used to output
  121. a specifically crafted CSS-styled link you needed many different
  122. places in your application. In order to fit your logic in to
  123. CakePHP's existing helper structure, you'll need to create a new
  124. class in ``/app/View/Helper``. Let's call our helper LinkHelper. The
  125. actual PHP class file would look something like this::
  126. <?php
  127. /* /app/View/Helper/LinkHelper.php */
  128. class LinkHelper extends AppHelper {
  129. function makeEdit($title, $url) {
  130. // Logic to create specially formatted link goes here...
  131. }
  132. }
  133. .. note::
  134. Helpers must extend :php:class:`Helper` or implement all the callbacks
  135. in the :ref:`helper-api`.
  136. Including other Helpers
  137. -----------------------
  138. You may wish to use some functionality already existing in another
  139. helper. To do so, you can specify helpers you wish to use with a
  140. ``$helpers`` array, formatted just as you would in a controller::
  141. <?php
  142. /* /app/View/Helper/LinkHelper.php (using other helpers) */
  143. class LinkHelper extends AppHelper {
  144. public $helpers = array('Html');
  145. function makeEdit($title, $url) {
  146. // Use the HTML helper to output
  147. // formatted data:
  148. $link = $this->Html->link($title, $url, array('class' => 'edit'));
  149. return '<div class="editOuter">' . $link . '</div>';
  150. }
  151. }
  152. .. _using-helpers:
  153. Using your Helper
  154. -----------------
  155. Once you've created your helper and placed it in
  156. ``/app/View/Helper/``, you'll be able to include it in your
  157. controllers using the special variable :php:attr:`~Controller::$helpers`::
  158. <?php
  159. class PostsController extends AppController {
  160. public $helpers = array('Link');
  161. }
  162. Once your controller has been made aware of this new class, you can
  163. use it in your views by accessing an object named after the
  164. helper::
  165. <!-- make a link using the new helper -->
  166. <?php echo $this->Link->makeEdit('Change this Recipe', '/recipes/edit/5'); ?>
  167. Creating Functionality for All Helpers
  168. ======================================
  169. All helpers extend a special class, AppHelper (just like models
  170. extend AppModel and controllers extend AppController). To create
  171. functionality that would be available to all helpers, create
  172. ``/app/View/Helper/AppHelper.php``::
  173. <?php
  174. class AppHelper extends Helper {
  175. function customMethod () {
  176. }
  177. }
  178. .. _helper-api:
  179. Helper API
  180. ==========
  181. .. php:class:: Helper
  182. The base class for Helpers. It provides a number of utility methods and
  183. features for loading other helpers.
  184. .. php:method:: webroot($file)
  185. Resolve a file name to the webroot of the application. If a theme is active
  186. and the file exists in the current theme's webroot, the path to the themed
  187. file will be returned.
  188. .. php:method:: url($url, $full = false)
  189. Generates an HTML escaped URL, delgates to :php:meth:`Router::url()`.
  190. .. php:method:: value($options = array(), $field = null, $key = 'value')
  191. Get the value for a given input name.
  192. .. php:method:: domId($options = null, $id = 'id')
  193. Generate a CamelCased id value for the currently selected field.
  194. Overriding this method in your AppHelper will allow you to change
  195. how CakePHP generates ID attributes.
  196. Callbacks
  197. ---------
  198. .. php:method:: beforeRender($viewFile)
  199. The beforeRender method is called after the controller's
  200. beforeRender method but before the controller's renders views and
  201. layout. Receives the file being rendered as an argument.
  202. .. php:method:: afterRender($viewFile)
  203. Is called after the view has been rendered but before layout rendering has
  204. started.
  205. .. php:method:: beforeLayout($layoutFile)
  206. Is called before layout rendering starts. Receives the layout filename as an
  207. argument.
  208. .. php:method:: afterLayout($layoutFile)
  209. Is called after layout rendering is complete. Receives the layout filename as an
  210. argument.
  211. Core Helpers
  212. ============
  213. :doc:`/core-libraries/helpers/cache`
  214. Used by the core to cache view content.
  215. :doc:`/core-libraries/helpers/form`
  216. Creates HTML forms and form elements that self populate and handle
  217. validation problems.
  218. :doc:`/core-libraries/helpers/html`
  219. Convenience methods for crafting well-formed markup. Images, links,
  220. tables, header tags and more.
  221. :doc:`/core-libraries/helpers/js`
  222. Used to create Javascript compatible with various Javascript
  223. libraries.
  224. :doc:`/core-libraries/helpers/number`
  225. Number and currency formatting.
  226. :doc:`/core-libraries/helpers/paginator`
  227. Model data pagination and sorting.
  228. :doc:`/core-libraries/helpers/rss`
  229. Convenience methods for outputting RSS feed XML data.
  230. :doc:`/core-libraries/helpers/session`
  231. Access for reading session values in views.
  232. :doc:`/core-libraries/helpers/text`
  233. Smart linking, highlighting, word smart truncation.
  234. :doc:`/core-libraries/helpers/time`
  235. Proximity detection (is this next year?), nice string
  236. formatting(Today, 10:30 am) and time zone conversion.