Zend_Session-BasicUsage.xml 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. <sect1 id="zend.session.basicusage">
  2. <title>Базовое использование<!--Basic Usage--></title>
  3. <para>
  4. <code>Zend_Session_Namespace</code> создает экземпляры контейнеров,
  5. предоставляющих основной API для работы с данными сессии в Zend
  6. Framework. Пространства имен используются для разделения всех данных
  7. сессии, несмотря на то, что есть пространство имен по умолчанию для тех,
  8. кому нужно только одно пространство имен для всех данных сессии.
  9. <code>Zend_Session</code> использует расширение ext/session и его
  10. суперглобальный массив <varname>$_SESSION</varname> в качестве механизма
  11. хранения постоянных данных сессии. Несмотря на то, что
  12. <varname>$_SESSION</varname> остается доступным в глобальном пространстве
  13. имен, разработчики должны избегать прямого обращения к нему с тем, чтобы
  14. можно было наиболее безопасно и эффективно использовать возможности
  15. <code>Zend_Session</code> и <code>Zend_Session_Namespace</code> для
  16. работы с сессиями.
  17. <!--
  18. <code>Zend_Session_Namespace</code> creates instances of containers providing the primary API for manipulating
  19. session data in Zend Framework. Namespaces are used to segregate all session data, although a default
  20. namespace exists for those who only want one namespace for all their session data. <code>Zend_Session</code>
  21. utilizes ext/session and its special <varname>$_SESSION</varname> superglobal as the storage mechanism for session
  22. state data. While <varname>$_SESSION</varname> is still available in PHP's global namespace, developers should refrain
  23. from directly accessing it, so that <code>Zend_Session</code> and <code>Zend_Session_Namespace</code> can most
  24. effectively and securely provide its suite of session related functionality.
  25. -->
  26. </para>
  27. <sect2 id="zend.session.basicexamples">
  28. <title>Учебные примеры<!--Tutorial Examples--></title>
  29. <para>
  30. Если при инстанцировании Zend_Session не было указано пространство
  31. имен, то все данные будут неявным образом сохранены в пространстве
  32. имен "<code>Default</code>". <code>Zend_Session</code> не
  33. предназначен для работы с содержимым контейнера пространства имен
  34. сессии напрямую. Вместо этого мы используем
  35. <code>Zend_Session_Namespace</code>. Пример ниже демонстрирует
  36. использование пространства имен по умолчанию и показывает, как
  37. подсчитывать количество просмотров страниц пользователем на сайте.
  38. Для тестирования этого примера добавьте следующий код в
  39. файл загрузки:
  40. <!--
  41. If no namespace is specified when instantiating Zend_Session, all data will be transparently stored in a
  42. namespace called "<code>Default</code>". <code>Zend_Session</code> is not intended to work directly on the
  43. contents of session namespace containers. Instead, we use <code>Zend_Session_Namespace</code>. The example
  44. below demonstrates use of this default namespace, showing how to count the number of times a user views
  45. pages on your website. To test this example, add the following code to your ZF bootstrap area:
  46. -->
  47. </para>
  48. <example>
  49. <title>Подсчет количества просмотров страниц<!--Counting Page Views--></title>
  50. <programlisting language="php">
  51. <![CDATA[<?php
  52. require_once 'Zend/Session.php';
  53. $defaultNamespace = new Zend_Session_Namespace('Default');
  54. // используется "магический" метод __isset() в Zend_Session_Namespace:
  55. if (isset($defaultNamespace->numberOfPageRequests)) {
  56. // будет увеличиваться на единицу при каждой загрузке страницы.
  57. $defaultNamespace->numberOfPageRequests++;
  58. } else {
  59. $defaultNamespace->numberOfPageRequests = 1; // начальное значение
  60. }
  61. echo "Запросов к странице за эту сессию: ", $defaultNamespace->numberOfPageRequests;
  62. ?>]]></programlisting>
  63. </example>
  64. <para>
  65. Одним из многих преимуществ Zend_Session_Namespace
  66. является то, что при его использовании различными модулями
  67. приложения достигается инкапсуляциия принадлежащих им данных сессий.
  68. Конструктору Zend_Session можно передавать необязательный аргумент
  69. $namespace, который позволяет другим компонентам, модулям и
  70. разрабочикам кода быть уверенным в том, что их данные
  71. защищены отделением от других областей данных, используемых другими
  72. компонентами, модулями и кодами разработчиков. Пространства имен
  73. представляют собой эффективный и доступный способ защиты данных
  74. сессий от случайных изменений. Имена пространств имен должны быть
  75. непустыми строками, не начинающимися со знака подчеркивания. Только
  76. основные компоненты, включенные в Zend Framework, должны
  77. использовать имена пространств имен, начинающиеся с 'Zend_'.
  78. <!--
  79. One of the many benefits of Zend_Session_Namespace results when multiple modules use Zend_Session_Namespace
  80. and obtain data encapsulation for their session data. Zend_Session can be passed an optional $namespace
  81. argument in the constructor, which allows other components, modules, and developer specific code to be
  82. assured that their data is protected by a partition between data areas used by other components, modules,
  83. and developer code. Namespacing provides an effective and popular way to "secure" a subset of session state
  84. data against accidental changes. Namespace names are restricted to character sequences represented as
  85. non-empty PHP strings that do not begin with an underscore ('_') character. Only core components included in
  86. Zend Framework should use namespace names starting with 'Zend_'.
  87. -->
  88. </para>
  89. <example>
  90. <title>Новый подход: избежание конфликтов с помощью пространств имен<!--New Way: Namespaces Avoid Collisions--></title>
  91. <programlisting language="php">
  92. <![CDATA[<?php
  93. // in the Zend_Auth component
  94. require_once 'Zend/Session.php';
  95. $authNamespace = new Zend_Session_Namespace('Zend_Auth');
  96. $authNamespace->user = "myusername";
  97. // in a web services component
  98. $webServiceNamespace = new Zend_Session_Namespace('Some_Web_Service');
  99. $webServiceNamespace->user = "mywebusername";
  100. ?>]]></programlisting>
  101. </example>
  102. <para>
  103. Пример выше приводит к тому же результату, что и код ниже, за тем
  104. исключением, что объекты сессий сохраняют инкапсуляцию сессионных
  105. данных внутри их пространств имен.
  106. <!--
  107. The example above achieves the same effect as the code below, except that the session objects above preserve
  108. encapsulation of session data within their respective namespaces.
  109. -->
  110. </para>
  111. <example>
  112. <title>Старый подход: обращение к сессиям PHP<!--Old Way: PHP Session Access--></title>
  113. <programlisting language="php">
  114. <![CDATA[<?php
  115. $_SESSION['Zend_Auth']['user'] = "myusername";
  116. $_SESSION['Some_Web_Service']['user'] = "mywebusername";
  117. ?>]]></programlisting>
  118. </example>
  119. </sect2>
  120. <sect2 id="zend.session.iteration">
  121. <title>Итерация по пространствам имен<!--Iterating Over Session Namespaces--></title>
  122. <para>
  123. <code>Zend_Session_Namespace</code> предоставляет полный интерфейс
  124. <ulink url="http://www.php.net/~helly/php/ext/spl/interfaceIteratorAggregate.html">IteratorAggregate</ulink>,
  125. включая поддержку выражения <code>foreach</code>:
  126. <!--
  127. <code>Zend_Session_Namespace</code> provides the full
  128. <ulink url="http://www.php.net/~helly/php/ext/spl/interfaceIteratorAggregate.html">IteratorAggregate interface</ulink>
  129. , including support for the <code>foreach</code> statement:
  130. -->
  131. </para>
  132. <example>
  133. <title>Итерация по сессии<!--Session Iteration--></title>
  134. <programlisting language="php">
  135. <![CDATA[<?php
  136. // Zend_Session is iteratable
  137. require_once 'Zend/Session.php';
  138. $aNamespace = new Zend_Session_Namespace('some_namespace_with_data_present');
  139. foreach ($aNamespace as $index => $value) {
  140. echo "aNamespace->$index = '$value';\n";
  141. }
  142. ?>]]></programlisting>
  143. </example>
  144. </sect2>
  145. <sect2 id="zend.session.accessors">
  146. <title>Методы доступа для пространств имен<!--Accessors for Session Namespaces--></title>
  147. <para>
  148. Обычные методы доступа доступны через "магические" методы (magic
  149. methods) __set(), __unset(), __isset() и __get(). "Магические"
  150. методы не должны использоваться напрямую, кроме как внутри
  151. подклассов Zend_Session. Вместо этого используйте обычные операторы
  152. для вызова этих "магических" методов, например:
  153. <!--
  154. The usual accessors are available, via the __set(), __unset(), __isset(), and __get() magic methods. The
  155. magic methods should not be used directly, except from within a subclass of Zend_Session. Instead, use the
  156. normal operators to invoke these magic methods, such as:
  157. -->
  158. </para>
  159. <example>
  160. <title>Доступ к сессионным данным<!--Accessing Session Data--></title>
  161. <programlisting language="php">
  162. <![CDATA[<?php
  163. $object->property = $value;
  164. echo (isset($object->property) ? 'set' : 'unset');
  165. ?>]]></programlisting>
  166. </example>
  167. </sect2>
  168. </sect1>