2
0

Zend_Registry.xml 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. <sect1 id="zend.registry.using">
  2. <title>Использование реестра<!--Using the Registry--></title>
  3. <para>
  4. Реестр является контейнером для хранения объектов и значений в
  5. среде приложения. Посредством сохранения значения в реестре
  6. объект становится доступным всему приложению. Этот механизм является
  7. альтернативой использованию глобальных переменных.
  8. <!--
  9. The registry is a container for storing objects and values in the
  10. application space. By storing the value in the registry, the same
  11. object is always available throughout your application.
  12. This mechanism is an alternative to using global storage.
  13. -->
  14. </para>
  15. <para>
  16. Типовое использование реестра - использование статических методов класса
  17. Zend_Registry. Вы можете также обращаться к элементам, сохраненным в
  18. реестре, как к элементам массива, поскольку класс реестра наследует от
  19. ArrayObject.
  20. <!--
  21. The typical usage of the registry is through static methods in the
  22. Zend_Registry class. Alternatively, the class is an array object,
  23. so you can access elements stored within it with a convenient
  24. array-like interface.
  25. -->
  26. </para>
  27. <sect2 id="zend.registry.using.storing">
  28. <title>Установка значений в реестре<!--Setting Values in the Registry--></title>
  29. <para>
  30. Для того, чтобы сохранить значение в реестре, используйте
  31. статический метод <code>set()</code>.
  32. <!--
  33. To store an entry in the registry, use the static method
  34. <code>set()</code>.
  35. -->
  36. </para>
  37. <example id="zend.registry.using.storing.example">
  38. <title>Пример использования метода set()<!--Example of set() method--></title>
  39. <programlisting language="php"><![CDATA[<?php
  40. Zend_Registry::set('index', $value);
  41. ?>]]></programlisting>
  42. </example>
  43. <para>
  44. Сохраняемое значение может быть объектом, массивом или скаляром. Вы
  45. можете изменить значение, сохраненное под определенным индексом в
  46. реестре, устанавливая новое значение методом <code>set()</code>.
  47. <!--
  48. The value can be an object, an array, or a scalar.
  49. You can change the value stored in a specific entry of
  50. the registry by using <code>set()</code> to set it
  51. to a new value.
  52. -->
  53. </para>
  54. <para>
  55. Индекс может быть строкой или целочисленным значением, как в обычном
  56. массиве.
  57. <!--
  58. The index can be a scalar, either string or integer,
  59. like an ordinary array.
  60. -->
  61. </para>
  62. </sect2>
  63. <sect2 id="zend.registry.using.retrieving">
  64. <title>Получение значений из реестра<!--Getting Values from the Registry--></title>
  65. <para>
  66. Для того, чтобы получить запись из реестра, используйте статический
  67. метод <code>get()</code>.
  68. <!--
  69. To retrieve an entry from the registry, use the static method
  70. <code>get()</code>.
  71. -->
  72. </para>
  73. <example id="zend.registry.using.retrieving.example">
  74. <title>Пример использования метода get()<!--Example of get() method--></title>
  75. <programlisting language="php"><![CDATA[<?php
  76. $value = Zend_Registry::get('index');
  77. ?>]]></programlisting>
  78. </example>
  79. <para>
  80. Метод <code>getInstance()</code> возвращает статический объект
  81. реестра.
  82. <!--
  83. The <code>getInstance()</code> method returns the static registry object.
  84. -->
  85. </para>
  86. <para>
  87. По объекту реестра можно производить итерацию.
  88. <!--
  89. A registry object is iterable.
  90. -->
  91. </para>
  92. <example id="zend.registry.using.retrieving.example-iterating">
  93. <title>Пример итерации по реестру<!--Example of iterating over the registry--></title>
  94. <programlisting language="php"><![CDATA[<?php
  95. $registry = Zend_Registry::getInstance();
  96. foreach ($registry as $index => $value) {
  97. echo "Registry index $index contains:\n";
  98. var_dump($value);
  99. }
  100. ?>]]></programlisting>
  101. </example>
  102. </sect2>
  103. <sect2 id="zend.registry.using.constructing">
  104. <title>Создание объекта реестра<!--Constructing a Registry Object--></title>
  105. <para>
  106. Кроме доступа к статическому реестру через статические методы, вы
  107. можете также непосредственно создавать экземпляр реестра и
  108. использовать его как объект.
  109. <!--
  110. In addition to accessing the static registry through
  111. static methods, you can create an instance directly and
  112. use it as an object.
  113. -->
  114. </para>
  115. <para>
  116. Экземпляр реестра, к которому вы обращаетесь через статические
  117. методы, просто является одним из таких экземпляров. Это сделано в
  118. целях удобства, т.к. оно сохраняется статически и вы можете
  119. обращаться к нему из любого места своего приложения.
  120. <!--
  121. The registry instance you access through the
  122. static methods is simply one such instance, and it is
  123. for convenience that it is stored statically, so you
  124. can access it from anywhere in your appliation.
  125. -->
  126. </para>
  127. <para>
  128. Используйте традиционный конструктор <code>new</code> для создания
  129. экземпляра реестра. Это дает возможность иницизировать записи в
  130. реестре так же, как в массиве.
  131. <!--
  132. Use a traditional <code>new</code> constructor to create
  133. an instance of the registry. This gives you the opportunity
  134. to initialize the entries in the registry as an associatve
  135. array.
  136. -->
  137. </para>
  138. <example id="zend.registry.using.constructing.example">
  139. <title>Пример создания реестра<!--Example of constructing a registry--></title>
  140. <programlisting language="php"><![CDATA[<?php
  141. $registry = new Zend_Registry(array('index' => $value));
  142. ?>]]></programlisting>
  143. </example>
  144. <para>
  145. После создания экземпляра вы можете использовать его с применением
  146. методов доступа ArrayObject, или установить его как
  147. статический экземпляр, используя статический метод
  148. <code>setInstance()</code>.
  149. <!--
  150. After constructing this instance, you can use it using
  151. array-object methods, or you can set this instance
  152. to become the static instance using the static method
  153. <code>setInstance()</code>.
  154. -->
  155. </para>
  156. <example id="zend.registry.using.constructing.example-setinstance">
  157. <title>Пример инициализации статического реестра<!--Example of initializing the static registry--></title>
  158. <programlisting language="php"><![CDATA[<?php
  159. $registry = new Zend_Registry(array('index' => $value));
  160. Zend_Registry::setInstance($registry);
  161. ?>]]></programlisting>
  162. </example>
  163. <para>
  164. Метод <code>setInstance()</code> бросает исключение Zend_Exception,
  165. если статический реестр уже был проинициализирован до
  166. первого обращения к нему.
  167. <!--
  168. The <code>setInstance()</code> method throws a Zend_Exception
  169. if the static registry has already been initialized by its
  170. first access.
  171. -->
  172. </para>
  173. </sect2>
  174. <sect2 id="zend.registry.using.array-access">
  175. <title>Доступ к реестру как к массиву<!--Accessing the Registry as an Array--></title>
  176. <para>
  177. Если необходимо установить или получить несколько значений, то
  178. может быть удобным использовать для этого нотацию доступа к
  179. массивам.
  180. <!--
  181. If you have several values to get or set, you may find it
  182. convenient to access the registry with array notation.
  183. -->
  184. </para>
  185. <example id="zend.registry.using.array-access.example">
  186. <title>Пример доступа как к массиву<!--Example of array access--></title>
  187. <programlisting language="php"><![CDATA[<?php
  188. $registry = Zend_Registry::getInstance();
  189. $registry['index'] = $value;
  190. var_dump( $registry['index'] );
  191. ?>]]></programlisting>
  192. </example>
  193. </sect2>
  194. <sect2 id="zend.registry.using.array-object">
  195. <title>Доступ к реестру как к объекту <!--Accessing the Registry as an Object--></title>
  196. <para>
  197. К реестру можно обращаться так же, как к объекту, используя имена
  198. индексов как имена свойств объекта. Для этого нужно специальным
  199. образом создать объект, используя опцию
  200. <code>ArrayObject::ARRAY_AS_PROPS</code>, и инициализировать
  201. статический экземпляр. Необходимо сделать это до того, как будет
  202. сделано первое обращение к статическому реестру.
  203. <emphasis>Будьте осторожны</emphasis>, используя эту
  204. опцию, поскольку некоторые версии PHP имеют ошибки, связанные с этой
  205. опцией.
  206. <!--
  207. You may also find it convenient to access the registry
  208. in an object-oriented fashion, using index names as object
  209. properties.
  210. To do this, you need to specifically construct the registry
  211. object using the <code>ArrayObject::ARRAY_AS_PROPS</code> option,
  212. and initialize the static instance. You must do this before
  213. the static registry has been accessed for the first time.
  214. <emphasis>Beware</emphasis> of using this option,
  215. since some versions of PHP have bugs when using the registry
  216. with this option.
  217. -->
  218. </para>
  219. <example id="zend.registry.using.array-object.example">
  220. <title>Пример доступа как к объекту<!--Example of object access--></title>
  221. <programlisting language="php"><![CDATA[<?php
  222. // в загрузочном коде:
  223. $registry = new Zend_Registry(array(), ArrayObject::ARRAY_AS_PROPS)
  224. Zend_Registry::setInstance($registry);
  225. $registry->tree = 'apple';
  226. .
  227. .
  228. .
  229. // в различных функциях и где-либо еще в приложении:
  230. $registry = Zend_Registry::getInstance();
  231. echo $registry->tree; // выводит "apple"
  232. $registry->index = $value;
  233. var_dump($registry->index);
  234. ?>]]></programlisting>
  235. </example>
  236. </sect2>
  237. <sect2 id="zend.registry.using.isset">
  238. <title>Проверка существования индекса<!--Querying if an index exists--></title>
  239. <para>
  240. Для проверки того, существует ли в реестре значение под определенным
  241. индексом, используйте <code>isRegistered()</code>.
  242. <!--
  243. To find out if a particular index in the registry
  244. has a value, use the static method <code>isRegistered()</code>.
  245. -->
  246. </para>
  247. <example id="zend.registry.using.isset.example-isregistered">
  248. <title>Пример использования метода isRegistered()<!--Example of isRegistered() method--></title>
  249. <programlisting language="php"><![CDATA[<?php
  250. if (Zend_Registry::isRegistered($index)) {
  251. $value = Zend_Registry::get($index);
  252. }
  253. ?>]]></programlisting>
  254. </example>
  255. <para>
  256. Для того, чтобы найти определенный индекс в объекте реестра,
  257. используйте конструкцию isset(), как в случае обычного массива.
  258. <!--
  259. To find out if a particular index in a registry
  260. array-object has a value, use <code>isset()</code>
  261. like you would with an ordinary array.
  262. -->
  263. </para>
  264. <example id="zend.registry.using.isset.example-isset">
  265. <title>Пример использования метода isset()<!--Example of isset() method--></title>
  266. <programlisting language="php"><![CDATA[<?php
  267. $registry = Zend_Registry::getInstance();
  268. // используется синтаксис доступа к массиву
  269. if (isset($registry['index'])) {
  270. var_dump( $registry['index'] );
  271. }
  272. // используется синтаксис доступа к объекту (должен быть включен)
  273. if (isset($registry->index)) {
  274. var_dump( $registry->index );
  275. }
  276. ?>]]></programlisting>
  277. </example>
  278. </sect2>
  279. <sect2 id="zend.registry.using.subclassing">
  280. <title>Создание подклассов<!--Extending the Registry--></title>
  281. <para>
  282. Статический реестр является экземпляром класса Zend_Registry. Если
  283. вы хотите добавить в реестр дополнительный функционал, то можете
  284. создать класс, наследующий от Zend_Registry и определить его как
  285. используемый для статического реестра. Используйте статический метод
  286. <code>setClassName()</code> для установки класса. Этот класс должен
  287. наследовать от Zend_Registry.
  288. <!--
  289. The static registry is an instance of the class Zend_Registry.
  290. If you want to add functionality to the registry, you can
  291. create a class that extends Zend_Registry, and then you can
  292. specify this class as the class to use for the static registry.
  293. Use the static method <code>setClassName()</code> to specify
  294. the class. The class must extend Zend_Registry.
  295. -->
  296. </para>
  297. <example id="zend.registry.using.subclassing.example">
  298. <title>Пример установки класса статического реестра<!--Example of specifying the static registry's class name--></title>
  299. <programlisting language="php"><![CDATA[<?php
  300. Zend_Registry::setClassName('My_Registry');
  301. Zend_Registry::set('index', $value);
  302. ?>]]></programlisting>
  303. </example>
  304. <para>
  305. Реестр бросает исключение, если вы пытаетесь установить имя класса,
  306. используемого для статического реестра, после того, как было первое
  307. обращение к реестру. Рекомендуется устанавливать имя класса в
  308. загрузочном коде.
  309. <!--
  310. The registry throws a Zend_Exception if you try to set the
  311. classname after the registry has been accessed for the first time.
  312. It is recommended that you specify the classname for your
  313. static registry in your application bootstrap.
  314. -->
  315. </para>
  316. </sect2>
  317. <sect2 id="zend.registry.using.unsetting">
  318. <title>Уничтожение статического реестра<!--Unsetting the Static Registry--></title>
  319. <para>
  320. Хотя обычно в этом нет необходимости, вы можете уничтожить
  321. статический экземпляр реестра. Для этого используйте метод
  322. <code>_unsetInstance()</code>.
  323. <!--
  324. Although it is not normally necessary, you can
  325. unset the static instance of the registry.
  326. Use the static method <code>_unsetInstance()</code>.
  327. -->
  328. </para>
  329. <note>
  330. <title>Угроза потери данных<!--Data loss risk--></title>
  331. <para>
  332. Когда используете <code>_unsetInstance()</code>, все данные
  333. в статическом реестре удаляются и не могут быть восстановлены.
  334. <!--
  335. When you use <code>_unsetInstance()</code>,
  336. all data in the static registry are
  337. discarded and cannot be recovered.
  338. -->
  339. </para>
  340. </note>
  341. <para>
  342. Вы можете применять данный метод, если, например, хотите
  343. использовать <code>setInstance()</code> или
  344. <code>setClassName()</code> после того, как был проинциализирован
  345. объект статического реестра. Уничтожение статического экземпляра
  346. дает возможность использовать эти методы.
  347. <!--
  348. You might use this method, for example, if you want to
  349. use <code>setInstance()</code> or <code>setClassName()</code>
  350. after the static registry object has been initialized.
  351. Unsetting the static instance allows you to use these methods.
  352. -->
  353. </para>
  354. <example id="zend.registry.using.unsetting.example">
  355. <title>Пример использования метода _unsetInstance()<!--Example of _unsetInstance() method--></title>
  356. <programlisting language="php"><![CDATA[<?php
  357. Zend_Registry::set('index', $value);
  358. Zend_Registry::_unsetInstance();
  359. // изменение класса
  360. Zend_Registry::setClassName('My_Registry');
  361. Zend_Registry::set('index', $value);
  362. ?>]]></programlisting>
  363. </example>
  364. </sect2>
  365. </sect1>
  366. <!--
  367. vim:se ts=4 sw=4 et:
  368. -->