PageRenderTime 47ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/ru/controllers/components.rst

https://bitbucket.org/cakephp/docs
ReStructuredText | 260 lines | 193 code | 67 blank | 0 comment | 0 complexity | 71f6da149f818af421227522ec84dbe5 MD5 | raw file
  1. Компоненты
  2. ##########
  3. Компоненты - это "пакеты" логики, которые доступны разным контроллерам.
  4. Если вы часто делаете "копи паст" из контроллера в контроллер, то стоит
  5. задуматься над созданием компонентам, в котором будет описана часто используемая логика.
  6. В CakePHP есть фантастический набор основных компонентов, которые упрощают
  7. работу с такими задачами:
  8. - Безопастность(Security)
  9. - Сессии(Sessions)
  10. - Уровни доступа(Access control lists)
  11. - Почта(Emails)
  12. - Куки(Cookies)
  13. - Аутентификация(Authentication)
  14. - Обработка запроса(Request handling)
  15. Каждый из этих компонентов подробно описан в своей главе. А сейчас посмотрим, как создавать
  16. свои собственные компоненты. Создание компонентов сохраняет код контроллера чистым и
  17. позволяет повторно использовать в разных проектах.
  18. .. _configuring-components:
  19. Конфигурация Компонентов
  20. ========================
  21. Для многих компонентов доступна(или требуется) конфигурация.
  22. Например, компоненты :doc:`/core-libraries/components/authentication`,
  23. :doc:`/core-libraries/components/cookie` и :doc:`/core-libraries/components/email`
  24. требуют конфигурации. Конфигурация для этих компонентов и компонентов в целом обычно делается в
  25. ``$components`` массиве или в вашем методе контроллера ``beforeFilter()``::
  26. class PostsController extends AppController {
  27. public $components = array(
  28. 'Auth' => array(
  29. 'authorize' => array('controller'),
  30. 'loginAction' => array('controller' => 'users', 'action' => 'login')
  31. ),
  32. 'Cookie' => array('name' => 'CookieMonster')
  33. );
  34. Would be an example of configuring a component with the
  35. ``$components`` array. All core components allow their
  36. configuration settings to be set in this way. In addition you can
  37. configure components in your controller's ``beforeFilter()``
  38. method. This is useful when you need to assign the results of a
  39. function to a component property. The above could also be expressed
  40. as::
  41. public function beforeFilter() {
  42. $this->Auth->authorize = array('controller');
  43. $this->Auth->loginAction = array('controller' => 'users', 'action' => 'login');
  44. $this->Cookie->name = 'CookieMonster';
  45. }
  46. It's possible, however, that a component requires certain
  47. configuration options to be set before the controller's
  48. ``beforeFilter()`` is run. To this end, some components allow
  49. configuration options be set in the ``$components`` array::
  50. public $components = array('DebugKit.Toolbar' => array('panels' => array('history', 'session')));
  51. Consult the relevant documentation to determine what configuration
  52. options each component provides.
  53. Using Components
  54. ================
  55. Once you've included some components in your controller, using them is
  56. pretty simple. Each component you use is exposed as a property on your
  57. controller. If you had loaded up the :php:class:`SessionComponent` and
  58. the :php:class:`CookieComponent` in your controller, you could access
  59. them like so::
  60. class PostsController extends AppController {
  61. public $components = array('Session', 'Cookie');
  62. public function delete() {
  63. if ($this->Post->delete($this->request->data('Post.id')) {
  64. $this->Session->setFlash('Post deleted.');
  65. $this->redirect(array('action' => 'index'));
  66. }
  67. }
  68. .. note::
  69. Since both Models and Components are added to Controllers as
  70. properties they share the same 'namespace'. Be sure to not give a
  71. component and a model the same name.
  72. Loading components on the fly
  73. -----------------------------
  74. You might not need all of your components available on every controller action.
  75. In situations like this you can load a component at runtime using the
  76. :doc:`Component Collection </core-libraries/collections>`. From inside a
  77. controller you can do the following::
  78. $this->OneTimer = $this->Components->load('OneTimer');
  79. $this->OneTimer->getTime();
  80. Component Callbacks
  81. ===================
  82. Components also offer a few request life-cycle callbacks that allow them
  83. to augment the request cycle. See the base :ref:`component-api` for
  84. more information on the callbacks components offer.
  85. Creating a Component
  86. ====================
  87. Suppose our online application needs to perform a complex
  88. mathematical operation in many different parts of the application.
  89. We could create a component to house this shared logic for use in
  90. many different controllers.
  91. The first step is to create a new component file and class. Create
  92. the file in ``/app/Controller/Component/MathComponent.php``. The basic
  93. structure for the component would look something like this::
  94. class MathComponent extends Component {
  95. function doComplexOperation($amount1, $amount2) {
  96. return $amount1 + $amount2;
  97. }
  98. }
  99. .. note::
  100. All components must extend :php:class:`Component`. Failing to do this
  101. will trigger an exception.
  102. Including your component in your controllers
  103. --------------------------------------------
  104. Once our component is finished, we can use it in the application's
  105. controllers by placing the component's name (minus the "Component"
  106. part) in the controller's ``$components`` array. The controller will
  107. automatically be given a new attribute named after the component,
  108. through which we can access an instance of it::
  109. /* Make the new component available at $this->Math,
  110. as well as the standard $this->Session */
  111. public $components = array('Math', 'Session');
  112. Components declared in ``AppController`` will be merged with those
  113. in your other controllers. So there is no need to re-declare the
  114. same component twice.
  115. When including Components in a Controller you can also declare a
  116. set of parameters that will be passed on to the Component's
  117. constructor. These parameters can then be handled by
  118. the Component::
  119. public $components = array(
  120. 'Math' => array(
  121. 'precision' => 2,
  122. 'randomGenerator' => 'srand'
  123. ),
  124. 'Session', 'Auth'
  125. );
  126. The above would pass the array containing precision and
  127. randomGenerator to ``MathComponent::__construct()`` as the
  128. second parameter. By convention, any settings that have been passed
  129. that are also public properties on your component will have the values
  130. set based on the settings.
  131. Using other Components in your Component
  132. ----------------------------------------
  133. Sometimes one of your components may need to use another component.
  134. In this case you can include other components in your component the exact same
  135. way you include them in controllers - using the ``$components`` var::
  136. // app/Controller/Component/CustomComponent.php
  137. class CustomComponent extends Component {
  138. // the other component your component uses
  139. public $components = array('Existing');
  140. function initialize($controller) {
  141. $this->Existing->foo();
  142. }
  143. function bar() {
  144. // ...
  145. }
  146. }
  147. // app/Controller/Component/ExistingComponent.php
  148. class ExistingComponent extends Component {
  149. function initialize($controller) {
  150. $this->Parent->bar();
  151. }
  152. function foo() {
  153. // ...
  154. }
  155. }
  156. .. _component-api:
  157. Component API
  158. =============
  159. .. php:class:: Component
  160. The base Component class offers a few methods for lazily loading other
  161. Components through :php:class:`ComponentCollection` as well as dealing
  162. with common handling of settings. It also provides prototypes for all
  163. the component callbacks.
  164. .. php:method:: __construct(ComponentCollection $collection, $settings = array())
  165. Constructor for the base component class. All ``$settings`` that
  166. are also public properties will have their values changed to the
  167. matching value in ``$settings``.
  168. Callbacks
  169. ---------
  170. .. php:method:: initialize($controller)
  171. The initialize method is called before the controller's
  172. beforeFilter method.
  173. .. php:method:: startup($controller)
  174. The startup method is called after the controller's beforeFilter
  175. method but before the controller executes the current action
  176. handler.
  177. .. php:method:: beforeRender($controller)
  178. The beforeRender method is called after the controller executes the
  179. requested action's logic but before the controller's renders views
  180. and layout.
  181. .. php:method:: shutdown($controller)
  182. The shutdown method is called before output is sent to browser.
  183. .. php:method:: beforeRedirect($controller, $url, $status=null, $exit=true)
  184. The beforeRedirect method is invoked when the controller's redirect
  185. method is called but before any further action. If this method
  186. returns false the controller will not continue on to redirect the
  187. request. The $url, $status and $exit variables have same meaning as
  188. for the controller's method. You can also return a string which
  189. will be interpreted as the url to redirect to or return associative
  190. array with key 'url' and optionally 'status' and 'exit'.
  191. .. meta::
  192. :title lang=en: Components
  193. :keywords lang=en: array controller,core libraries,authentication request,array name,access control lists,public components,controller code,core components,cookiemonster,login cookie,configuration settings,functionality,logic,sessions,cakephp,doc