| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464 |
- <sect1 id="zend.registry.using">
- <title>Использование реестра<!--Using the Registry--></title>
- <para>
- Реестр является контейнером для хранения объектов и значений в
- среде приложения. Посредством сохранения значения в реестре
- объект становится доступным всему приложению. Этот механизм является
- альтернативой использованию глобальных переменных.
- <!--
- The registry is a container for storing objects and values in the
- application space. By storing the value in the registry, the same
- object is always available throughout your application.
- This mechanism is an alternative to using global storage.
- -->
- </para>
- <para>
- Типовое использование реестра - использование статических методов класса
- Zend_Registry. Вы можете также обращаться к элементам, сохраненным в
- реестре, как к элементам массива, поскольку класс реестра наследует от
- ArrayObject.
- <!--
- The typical usage of the registry is through static methods in the
- Zend_Registry class. Alternatively, the class is an array object,
- so you can access elements stored within it with a convenient
- array-like interface.
- -->
- </para>
- <sect2 id="zend.registry.using.storing">
- <title>Установка значений в реестре<!--Setting Values in the Registry--></title>
- <para>
- Для того, чтобы сохранить значение в реестре, используйте
- статический метод <code>set()</code>.
- <!--
- To store an entry in the registry, use the static method
- <code>set()</code>.
- -->
- </para>
- <example id="zend.registry.using.storing.example">
- <title>Пример использования метода set()<!--Example of set() method--></title>
- <programlisting language="php"><![CDATA[<?php
- Zend_Registry::set('index', $value);
- ?>]]></programlisting>
- </example>
- <para>
- Сохраняемое значение может быть объектом, массивом или скаляром. Вы
- можете изменить значение, сохраненное под определенным индексом в
- реестре, устанавливая новое значение методом <code>set()</code>.
- <!--
- The value can be an object, an array, or a scalar.
- You can change the value stored in a specific entry of
- the registry by using <code>set()</code> to set it
- to a new value.
- -->
- </para>
- <para>
- Индекс может быть строкой или целочисленным значением, как в обычном
- массиве.
- <!--
- The index can be a scalar, either string or integer,
- like an ordinary array.
- -->
- </para>
- </sect2>
- <sect2 id="zend.registry.using.retrieving">
- <title>Получение значений из реестра<!--Getting Values from the Registry--></title>
- <para>
- Для того, чтобы получить запись из реестра, используйте статический
- метод <code>get()</code>.
- <!--
- To retrieve an entry from the registry, use the static method
- <code>get()</code>.
- -->
- </para>
- <example id="zend.registry.using.retrieving.example">
- <title>Пример использования метода get()<!--Example of get() method--></title>
- <programlisting language="php"><![CDATA[<?php
- $value = Zend_Registry::get('index');
- ?>]]></programlisting>
- </example>
- <para>
- Метод <code>getInstance()</code> возвращает статический объект
- реестра.
- <!--
- The <code>getInstance()</code> method returns the static registry object.
- -->
- </para>
- <para>
- По объекту реестра можно производить итерацию.
- <!--
- A registry object is iterable.
- -->
- </para>
- <example id="zend.registry.using.retrieving.example-iterating">
- <title>Пример итерации по реестру<!--Example of iterating over the registry--></title>
- <programlisting language="php"><![CDATA[<?php
- $registry = Zend_Registry::getInstance();
- foreach ($registry as $index => $value) {
- echo "Registry index $index contains:\n";
- var_dump($value);
- }
- ?>]]></programlisting>
- </example>
- </sect2>
- <sect2 id="zend.registry.using.constructing">
- <title>Создание объекта реестра<!--Constructing a Registry Object--></title>
- <para>
- Кроме доступа к статическому реестру через статические методы, вы
- можете также непосредственно создавать экземпляр реестра и
- использовать его как объект.
- <!--
- In addition to accessing the static registry through
- static methods, you can create an instance directly and
- use it as an object.
- -->
- </para>
- <para>
- Экземпляр реестра, к которому вы обращаетесь через статические
- методы, просто является одним из таких экземпляров. Это сделано в
- целях удобства, т.к. оно сохраняется статически и вы можете
- обращаться к нему из любого места своего приложения.
- <!--
- The registry instance you access through the
- static methods is simply one such instance, and it is
- for convenience that it is stored statically, so you
- can access it from anywhere in your appliation.
- -->
- </para>
- <para>
- Используйте традиционный конструктор <code>new</code> для создания
- экземпляра реестра. Это дает возможность иницизировать записи в
- реестре так же, как в массиве.
- <!--
- Use a traditional <code>new</code> constructor to create
- an instance of the registry. This gives you the opportunity
- to initialize the entries in the registry as an associatve
- array.
- -->
- </para>
- <example id="zend.registry.using.constructing.example">
- <title>Пример создания реестра<!--Example of constructing a registry--></title>
- <programlisting language="php"><![CDATA[<?php
- $registry = new Zend_Registry(array('index' => $value));
- ?>]]></programlisting>
- </example>
- <para>
- После создания экземпляра вы можете использовать его с применением
- методов доступа ArrayObject, или установить его как
- статический экземпляр, используя статический метод
- <code>setInstance()</code>.
- <!--
- After constructing this instance, you can use it using
- array-object methods, or you can set this instance
- to become the static instance using the static method
- <code>setInstance()</code>.
- -->
- </para>
- <example id="zend.registry.using.constructing.example-setinstance">
- <title>Пример инициализации статического реестра<!--Example of initializing the static registry--></title>
- <programlisting language="php"><![CDATA[<?php
- $registry = new Zend_Registry(array('index' => $value));
- Zend_Registry::setInstance($registry);
- ?>]]></programlisting>
- </example>
- <para>
- Метод <code>setInstance()</code> бросает исключение Zend_Exception,
- если статический реестр уже был проинициализирован до
- первого обращения к нему.
- <!--
- The <code>setInstance()</code> method throws a Zend_Exception
- if the static registry has already been initialized by its
- first access.
- -->
- </para>
- </sect2>
- <sect2 id="zend.registry.using.array-access">
- <title>Доступ к реестру как к массиву<!--Accessing the Registry as an Array--></title>
- <para>
- Если необходимо установить или получить несколько значений, то
- может быть удобным использовать для этого нотацию доступа к
- массивам.
- <!--
- If you have several values to get or set, you may find it
- convenient to access the registry with array notation.
- -->
- </para>
- <example id="zend.registry.using.array-access.example">
- <title>Пример доступа как к массиву<!--Example of array access--></title>
- <programlisting language="php"><![CDATA[<?php
- $registry = Zend_Registry::getInstance();
- $registry['index'] = $value;
- var_dump( $registry['index'] );
- ?>]]></programlisting>
- </example>
- </sect2>
- <sect2 id="zend.registry.using.array-object">
- <title>Доступ к реестру как к объекту <!--Accessing the Registry as an Object--></title>
- <para>
- К реестру можно обращаться так же, как к объекту, используя имена
- индексов как имена свойств объекта. Для этого нужно специальным
- образом создать объект, используя опцию
- <code>ArrayObject::ARRAY_AS_PROPS</code>, и инициализировать
- статический экземпляр. Необходимо сделать это до того, как будет
- сделано первое обращение к статическому реестру.
- <emphasis>Будьте осторожны</emphasis>, используя эту
- опцию, поскольку некоторые версии PHP имеют ошибки, связанные с этой
- опцией.
- <!--
- You may also find it convenient to access the registry
- in an object-oriented fashion, using index names as object
- properties.
- To do this, you need to specifically construct the registry
- object using the <code>ArrayObject::ARRAY_AS_PROPS</code> option,
- and initialize the static instance. You must do this before
- the static registry has been accessed for the first time.
- <emphasis>Beware</emphasis> of using this option,
- since some versions of PHP have bugs when using the registry
- with this option.
- -->
- </para>
- <example id="zend.registry.using.array-object.example">
- <title>Пример доступа как к объекту<!--Example of object access--></title>
- <programlisting language="php"><![CDATA[<?php
- // в загрузочном коде:
- $registry = new Zend_Registry(array(), ArrayObject::ARRAY_AS_PROPS)
- Zend_Registry::setInstance($registry);
- $registry->tree = 'apple';
- .
- .
- .
- // в различных функциях и где-либо еще в приложении:
- $registry = Zend_Registry::getInstance();
- echo $registry->tree; // выводит "apple"
- $registry->index = $value;
- var_dump($registry->index);
- ?>]]></programlisting>
- </example>
- </sect2>
- <sect2 id="zend.registry.using.isset">
- <title>Проверка существования индекса<!--Querying if an index exists--></title>
- <para>
- Для проверки того, существует ли в реестре значение под определенным
- индексом, используйте <code>isRegistered()</code>.
- <!--
- To find out if a particular index in the registry
- has a value, use the static method <code>isRegistered()</code>.
- -->
- </para>
- <example id="zend.registry.using.isset.example-isregistered">
- <title>Пример использования метода isRegistered()<!--Example of isRegistered() method--></title>
- <programlisting language="php"><![CDATA[<?php
- if (Zend_Registry::isRegistered($index)) {
- $value = Zend_Registry::get($index);
- }
- ?>]]></programlisting>
- </example>
- <para>
- Для того, чтобы найти определенный индекс в объекте реестра,
- используйте конструкцию isset(), как в случае обычного массива.
- <!--
- To find out if a particular index in a registry
- array-object has a value, use <code>isset()</code>
- like you would with an ordinary array.
- -->
- </para>
- <example id="zend.registry.using.isset.example-isset">
- <title>Пример использования метода isset()<!--Example of isset() method--></title>
- <programlisting language="php"><![CDATA[<?php
- $registry = Zend_Registry::getInstance();
- // используется синтаксис доступа к массиву
- if (isset($registry['index'])) {
- var_dump( $registry['index'] );
- }
- // используется синтаксис доступа к объекту (должен быть включен)
- if (isset($registry->index)) {
- var_dump( $registry->index );
- }
- ?>]]></programlisting>
- </example>
- </sect2>
- <sect2 id="zend.registry.using.subclassing">
- <title>Создание подклассов<!--Extending the Registry--></title>
- <para>
- Статический реестр является экземпляром класса Zend_Registry. Если
- вы хотите добавить в реестр дополнительный функционал, то можете
- создать класс, наследующий от Zend_Registry и определить его как
- используемый для статического реестра. Используйте статический метод
- <code>setClassName()</code> для установки класса. Этот класс должен
- наследовать от Zend_Registry.
- <!--
- The static registry is an instance of the class Zend_Registry.
- If you want to add functionality to the registry, you can
- create a class that extends Zend_Registry, and then you can
- specify this class as the class to use for the static registry.
- Use the static method <code>setClassName()</code> to specify
- the class. The class must extend Zend_Registry.
- -->
- </para>
- <example id="zend.registry.using.subclassing.example">
- <title>Пример установки класса статического реестра<!--Example of specifying the static registry's class name--></title>
- <programlisting language="php"><![CDATA[<?php
- Zend_Registry::setClassName('My_Registry');
- Zend_Registry::set('index', $value);
- ?>]]></programlisting>
- </example>
- <para>
- Реестр бросает исключение, если вы пытаетесь установить имя класса,
- используемого для статического реестра, после того, как было первое
- обращение к реестру. Рекомендуется устанавливать имя класса в
- загрузочном коде.
- <!--
- The registry throws a Zend_Exception if you try to set the
- classname after the registry has been accessed for the first time.
- It is recommended that you specify the classname for your
- static registry in your application bootstrap.
- -->
- </para>
- </sect2>
- <sect2 id="zend.registry.using.unsetting">
- <title>Уничтожение статического реестра<!--Unsetting the Static Registry--></title>
- <para>
- Хотя обычно в этом нет необходимости, вы можете уничтожить
- статический экземпляр реестра. Для этого используйте метод
- <code>_unsetInstance()</code>.
- <!--
- Although it is not normally necessary, you can
- unset the static instance of the registry.
- Use the static method <code>_unsetInstance()</code>.
- -->
- </para>
- <note>
- <title>Угроза потери данных<!--Data loss risk--></title>
- <para>
- Когда используете <code>_unsetInstance()</code>, все данные
- в статическом реестре удаляются и не могут быть восстановлены.
- <!--
- When you use <code>_unsetInstance()</code>,
- all data in the static registry are
- discarded and cannot be recovered.
- -->
- </para>
- </note>
- <para>
- Вы можете применять данный метод, если, например, хотите
- использовать <code>setInstance()</code> или
- <code>setClassName()</code> после того, как был проинциализирован
- объект статического реестра. Уничтожение статического экземпляра
- дает возможность использовать эти методы.
- <!--
- You might use this method, for example, if you want to
- use <code>setInstance()</code> or <code>setClassName()</code>
- after the static registry object has been initialized.
- Unsetting the static instance allows you to use these methods.
- -->
- </para>
- <example id="zend.registry.using.unsetting.example">
- <title>Пример использования метода _unsetInstance()<!--Example of _unsetInstance() method--></title>
- <programlisting language="php"><![CDATA[<?php
- Zend_Registry::set('index', $value);
- Zend_Registry::_unsetInstance();
- // изменение класса
- Zend_Registry::setClassName('My_Registry');
- Zend_Registry::set('index', $value);
- ?>]]></programlisting>
- </example>
- </sect2>
- </sect1>
- <!--
- vim:se ts=4 sw=4 et:
- -->
|