PEAR Справочное руководство

Под редакцией

Translated by

25-02-2007

Авторские права

Авторские права на это руководство принадлежат PEAR Documentation Group (2001-2003). Это руководство может распространяться при условии соблюдения условий Open Publication License, версии 1.0 или более поздней (последняя версия лицензии доступна по адресу http://www.opencontent.org/openpub/).

Распространение существенно модифицированных версий этого документа без прямого разрешения правообладателя запрещено.

Распространение работ или производных работ в любой обычной (бумажной) форме без прямого разрешения правообладателя запрещено.

PEAR Documentation Group состоит из всех людей, которые принимали участие в составлении документации к PEAR. Официальные представители перечислены на первой странице. Если вы хотите связаться с группой - вам следует написать по адресу pear-doc@lists.php.net.


Содержание
Предисловие
Об этом руководстве
Структура руководства
Authors and Contributors
I. О PEAR
1. Введение
2. Установка
3. Техническая поддержка
4. Стандарты кодирования PEAR
5. Как принять участие в проекте PEAR
6. ЧаВО - Частозадаваемые вопросы
7. PEAR Group Administrative Documents
II. New Maintainers' Guide
8. Introduction
9. When to contribute (and when not to contribute)
10. Getting started with the community
11. The formal proposal process
12. Taking over an unmaintained package
III. Руководство разработчика
13. Введение
14. Значение PEAR для разработчиков
15. Добавление вашего кода
16. Файл описания пакета - package.xml
17. The package definition file package.xml, version 2.0
18. Публикация пакета
19. Supporting PEAR development
20. Recommendations
21. Writing documentation
IV. New features in PEAR 1.4
22. Introduction
23. Channels
24. Custom File Roles
25. Custom File Tasks
26. Post-installation Scripts
V. PEAR Компоненты ядра
27. Базовые классы PEAR
28. Классы PPM
VI. PEAR Пакеты программ
29. Аутентификация
30. Тестирование
31. Кэширование
32. Конфигурация
33. Консоль
34. Базы данных
35. Дата и время
36. Шифрование
37. Event
38. Форматы файлов
39. Файловая система
40. Gtk
41. Gtk2
42. HTML
43. HTTP
44. Изображения
45. Internationalization
46. Logging
47. Почта
48. Математика
49. Сеть
50. Числа
51. Финансовые транзакции
52. PEAR
53. PHP
54. QA Tools
55. Наука
56. Streams
57. Structures
58. System
59. Текст
60. Tools and Utilities
61. Validate
62. Web Services
63. XML
VII. PECL Пакеты программ
I. Imagick
II. KADM5
III. Radius
IV. Net_Gopher
V. PostScript document creation
VI. Satellite CORBA client extension
VII. PostgreSQL Session Save Handler
VIII. SPPLUS Payment System
IX. Net_Gopher
X. oggvorbis

Предисловие


Об этом руководстве

Это руководство создано с помощью XML с использованием DocBook XML DTD и DSSSL (Document Style and Semantics Specification Language) для форматирования. Утилиты, использовавшиеся для форматирования HTML и PDF версий: Jade, который создал James Clark и The Modular DocBook Stylesheets, которые создал Norman Walsh.

Руководство основывается на большом объеме работы, которую в свое время сделали участники PHP Documentation Group. Подробнее читайте здесь - About the PHP manual.


Структура руководства

Здесь вы сможете найти описание обшей структуры, разметки и соглашений, которые используются в руководстве по PEAR. Руководство разделено на 5 основных частей:

  • О PEAR

    Эта секция содержит небольшой вступление на тему что такое PEAR и что он может предложить. В нее также включена общая информация об установке и использовании PEAR, вариантах поддержки и ответы на часто задаваемые вопросы о PEAR.

  • Основные компоненты

    Эта секция содержит документацию по базовым классам PEAR. Эти классы являются базовыми для каждого класса PEAR, понимание их основ позволит вам использовать PEAR. Обсуждаемые темы включают: базу PEAR, администрирование PEAR, обработку ошибок с помощью PEAR_Error и команды системы. Эти классы поставляются вместе с релизами PHP.

  • Пакеты

    Существует много пакетов PEAR и их количество растет день ото дня. Почти каждый пакет документирован и почти каждый не ставится по умолчанию. Информацию об установке классов PEAR на вашей системе вы можете найти в главе Установка.

    Каждый документированный класс содержит основную документацию о функциях, которые он предоставляет. Может быть, также, дополнительная информация в виде введения, списка констант и примеров использования пакета. Дополнительная информация может присутствовать в исходниках пакета.

    Описание каждой функции может содержать некоторые или все из нижеперечисленных частей:

    • Обзор

      Содержит описание структуры и прототип функции.

    • Описание

      Содержит описание того, что делает эта функция.

    • Параметр

      Описывает каждый параметр функции с указанием имен и типов каждого из них. Перечислены обязательные и опциональные параметры.

    • Возвращаемое значение

      Описывает возвращаемое значение, если функция не завершается ошибкой.

    • Throws

      Описывает объекты класса PEAR_Error, возвращаемые в случае завершении функции с ошибкой.

    • Заметка

      Дополнительные заметки и информация о функции. Содержит пример, если фукнция может быть вызвана статически.

    • См. также

      Ссылки на другие функции и разделы руководства.

    • Пример

      Пример использование функции или класса.

  • Пакеты PECL

    Пакеты PECL - это обычные модули PHP, написанные на C. Структура документации аналогична описанной выше.

  • Участие в PEAR

    Содержит информацию о написании и добавлении в PEAR своих собственных пакетов.


Authors and Contributors

The following is a list of people that are helping to maintain this documentation. If you would like to contact one of them, please write to pear-doc@lists.php.net.

  • Lorenzo Alberton

  • Gregory Beaver

  • Daniel Convissor

  • David Costa

  • Thomas V.V. Cox

  • Christophe GeschИ

  • Martin Jansen

  • Alan Knowles

  • Clay Loveless

  • Alexander Merz

  • Stefan Neufeind

  • Jon Parise

  • Tobias Schlitt

  • Stephan Schmidt

  • Mika Tuupola

  • Michael Wallner

  • Christian Weiske

(In alphabetic order.)

I. О PEAR


Глава 1. Введение

PEAR посвящается

PEAR посвящается Malin Bakken, родившейся 21 ноября 1999 года (первые строки PEAR были написаны всего за два часа до её рождения).


Что это такое: PEAR?

PEAR - это аббревиатура от "PHP Extension and Application Repository" (Репозиторий приложений и модулей PHP).

PEAR - это:


Структурированная библиотека PHP-кода

Код в PEAR разделен на так называемые "пакеты". Каждый пакет - это отдельный проект со своей командой разработчиков, номером версии, циклом разработки, документацией и определенным отношением к остальным пакетам (включая возможные зависимости). Пакеты распространяются в виде архивов *.TAR.GZ, которые включают в себя описание пакета, и устанавливаются на вашей системе с помощью инсталлятора PEAR.

Есть два типа пакетов: пакеты исходного кода (содержат, соответственно, только исходники) и бинарные пакеты (содержат платформозависимые бинарные файлы и, возможно, их исходный код). Естественно, что установка пакетов, которые содержат код на C, из исходников требует присутствия среды для компиляции C-кода.

В PEAR существует определенное дерево пакетов, в котором каждой ветвью является часть имени пакета. Ветви разделяются по темам, их названия в именах пакетов разделяются символом подчеркивания. Например, "MP3_Id", "Archive_Tar" и "HTTP_Post".

Пакеты могут находиться в зависимости друг от друга, однако не существует какой-либо обязательной зависимости между пакетом и его "родителем" в дереве пакетов (например, "HTTP_Post" не зависит от "HTTP").

Несколько ветвей высшего уровня называются "суб-репозиториями" и выполняют специальные функции. На данный момент это: PECL, Gtk и App. Каждый из них достоин отдельной темы, поэтому за дополнительной информацией лучше обратиться в соответствующие разделы настоящей документации.

Руководство по стилю написания кода, Стандарт кодирования PEAR (или коротко - PCS), существует для облегчения совместной работы разработчиков PEAR, для повышения качества и портабельности, а также для того, чтобы помочь разработчикам в создании cтандартизированных программных интерфейсов. В пакетах, которые входят в PFC (The PHP Foundation Classes), стандарт кодирования соблюдается особо строго, для других - менее.


Распространение кода и управление пакетами

Все пакеты PEAR регистрируются и загружаются в центральную базу данных, которая доступна на pear.php.net. Сторонние пакеты с открытыми исходниками так же могут быть зарегистрированы и загружены. Пакеты с закрытыми исходниками PEAR предназначена только для кода с открытыми исходниками.

Pear.php.net предоставляет два варианта интерфейсов к базе данных PEAR: дружественный для пользователя интерфейс (HTML) и интерфейс для машины (на данный момент это XML-RPC). Загрузка пакетов осуществляется с помощью HTTP. Также, pear.php.net выполняет и другие функции:

Пакеты распространяются в виде архивов *.TAR.GZ с описанием в формате XML. Описание содержит информацию о пакете, список файлов и их предназначений, а также список зависимостей.


Базовые классы PHP

Базовые классы (The PHP Foundation Classes, PFC) - это подмножество PEAR, основными целями которого являются качество, универсальность, многофункциональность и совместимость. В том случае, если PHP и далее будет поставляться вместе с пакетами PEAR и установщиком, то этими пакетами непременно будут базовые классы.

Повышенное качество этих пакетов означает то, что ни один пакет с уровнем ниже "stable" не будет допущен в PFC.

Универсальность означает, что пакеты не должны без особых на то причин зависеть от любого вида внешнего окружения (например, формата вывода, операционной системы, веб-сервера, SAPI и др.)

Многофункциональность пакетов означает, что их удобно использовать в других пакетах, они имеют стабильный и стандартизированный API, предпочитают использовать устоявшиеся компоненты, а также не зависят от внешней среды (версии PHP, SAPI, операционной системы и др.)

Совместимость - это не просто поддержка синтаксиса и семантики предыдущих версий, это также заблаговременное планирование. Проектирование кода таким образом, что добавление новой функциональности не требует больших усилий, делает код "совместимым с будущими версиями".


Пакеты Gtk

Gtk

Пакеты Gtk - это пакеты, которые используют функциональность проекта PHP-GTK. Код в этом суб-репозитории следует стандарту кодирования PEAR.

На данный момент еще нет определенного плана о том, как они будут распространяться.


Глава 2. Установка

Эта глава описывает процесс установки пакетов PEAR.


Введение

В этой главе предполагается, что вы уже знакомы со структурой PEAR.

Базовая установка, которая поставляется вместе с дистрибутивом PHP как часть базовых классов, содержит инструменты, необходимые для запуска установки PEAR. Если у вас установлен один из последних дистрибутивов PHP4 - можете быть спокойны, базовая инсталляция PEAR уже установлена в вашей системе, если только вы не конфигурировали PHP с флагом '--without-pear'.

Пакеты, которые не входят в число базовых, могут быть установлены с помощью менеджера пакетов PEAR, который является подобием "apt-get" в Debian. Еще раз повторим: если у вас установлена одна из последних версий PHP (> 4.3.0pre1), то вы можете пропустить следующий параграф. Если же вы используете PHP 4.2.* или более раннюю версию, то вам придется установить менеджер пакетов вручную.

Кроме установки пакетов, менеджер пакетов PEAR также выполняет некоторые другие задачи: он может создавать новые пакеты на вашей машине, управлять реестром установленных пакетов, проверять зависимости и общаться со службой XML-RPC на pear.php.net для выполнения некоторых других задач.


Установка из командной строки

Замечание

Нижеследующее описание относится к последней версии менеджера пакетов PEAR.

Установка из командной строки - это самый простой способ установить пакеты PEAR в вашей системе: установщик соединяется с сервером PEAR через обычное HTTP-соединение, загружает пакет на вашу машину и устанавливает в указанное место.


Полуавтоматическая установка

Если вы загрузили пакет с pear.php.net в виде *.tar.gz, то вы так же можете установить его локально. Для этого, выполните следующую команду в шелле:


$ pear install <file>.tgz
      

Эта команда автоматически установит пакет без использования соединения с удаленным сервером. <file>.tgz - это имя пакета, который вы загрузили и хотите установить.


Глава 3. Техническая поддержка

В этой главе описываются способы получения технической поддержки в том случае, если у вас есть вопросы, касающиеся PEAR.


Списки рассылки

Обзор

В большинстве проектов с открытыми исходниками поддержка осуществляется с помощью списков рассылки. В случае PEAR, имеются пять списков рассылки:

Первые четыре списка рассылки предназначены для того, чтобы помочь вам, если у вас имеются какие-то вопросы. Пожалуйста, дочитайте эту главу до конца, чтобы понять какой из них подходит именно вам. Рассылка изменений в CVS предназначена для разработчиков PEAR: все добавления и изменения в системе контроля версий (CVS) отражаются в этом списке рассылки.

Вы можете подписаться на списки рассылки PEAR здесь.


Рассылка для пользователей PEAR

Рассылка для пользователей PEAR - это список рассылки, где вы можете задать вопрос, касающийся установки PEAR, использования конкретных пакетов и т.п.

Этот список рассылки не предназначен для вопросов по использования PHP. Для этого, пожалуйста, используйте php-general@lists.php.net.


Рассылка для тех, кто занимается документацией

Этот список рассылки предназначен для обсуждения вопросов, которые касаются документации по PEAR.

Если вы хотите помочь в документировании пакетов PEAR - пишите сюда.


Глава 4. Стандарты кодирования PEAR

Замечание: Стандарты кодирования PEAR используються в коде, который в итоге стает частью PEAR, который в свою очередь поставляеться с дистрибутивом PHP или доступен для скачивания через утилиты инсталяции PEAR.


Комментарии

Комментарии внутри кода классов должны соответствовать синтаксису комментариев PHPDoc, который напоминает Javadoc. За дополнительной информацией о PHPDoc обращайтесь сюда: http://www.phpdoc.org/

Дополнительные комментарии, кроме тех, что предусмотрены PHPDoc, только приветствуются. Основное правило в данном случае - каждая часть кода повышенной сложности должна быть прокомментирована до того, как вы забыли как она работает.

Подходят комментарии в стилях C (/* */) и C++ (//). Использование комментариев в стиле Perl/shell (#) не рекомендуется.


Блок комментариев в заголовке

Все базовые файлы исходного кода в PEAR должны содержать следующий ниже блок комментариев в заголовке:
/* vim: set expandtab tabstop=4 softtabstop=4 shiftwidth=4: */
// +----------------------------------------------------------------------+
// | PHP version 4                                                        |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2002 The PHP Group                                |
// +----------------------------------------------------------------------+
// | This source file is subject to version 2.0 of the PHP license,       |
// | that is bundled with this package in the file LICENSE, and is        |
// | available at through the world-wide-web at                           |
// | http://www.php.net/license/2_02.txt.                                 |
// | If you did not receive a copy of the PHP license and are unable to   |
// | obtain it through the world-wide-web, please send a note to          |
// | license@php.net so we can mail you a copy immediately.               |
// +----------------------------------------------------------------------+
// | Authors: Original Author <author@example.com>                        |
// |          Your Name <you@example.com>                                 |
// +----------------------------------------------------------------------+
//
// $Id$

Нет четкого правила, которое определяет момент, когда новый разработчик должен быть добавлен в список авторов данного файла. В общем случае, его внос в изменения этого файла должен относиться к категории "значительных" (т.е. около 10%-20% процентов кода). Исключения могут быть в случае переписывания функций или добавления новой логики.

Простая реорганизация кода и исправление ошибок не приводит к добавлению нового участника в список авторов.

Файлы, которые не входят в базовую часть PEAR должны такой же блок комментариев в заголовке, включая авторские права, лицензию и список авторов. Комментарии должны быть отформатированы для того, чтобы сохранять свою целостность.


Использование CVS

Эта часть касается только пакетов, использующих CVS на cvs.php.net.

Включайте ключевое слово CVS - $Id$ в каждый файл. Добавьте эту метку в каждый файл, если там ее еще нет или исправьте уже существующую запись "Last Modified:" и т.п.).

В оставшейся части этой главы предполагается, что вы имеете представление о тэгах CVS и ветках (branches).

Тэги CVS предназначены для того, чтобы пометить файлы, которые принадлежат к конкретному релизу. Ниже приводится список необходимых и рекомендуемых тэгов:

Обязательным является только тэг RELEASE, остальные рекомендуются для вашего же удобства.

Пример того, как пометить тэгом релиза 1.2 пакет "Money_Fast":

Сделав так, вы получаете возможность использовать веб-сайт PEAR для дальнейшего процесса выпуска релизов.

Пример создания ветки для QA:

Тэг "QA_2_0_BP" - это тэг ветки. Рекомендуется всегда выделять ветки этим тэгом. Служебные ветви (MAINT branches) могут быть отмечены как релиз и без использования этого тэга.


Соглашения об именах

В общем случае, имена классов, функций и переменных всегда должны быть "говорящими" для того, чтобы читатель мог сразу понять для чего они используются.


Глава 5. Как принять участие в проекте PEAR

Этот раздел расказывает о том, каким образом вы можете принять участие в проекте PEAR.


Предложение патчей

Если вы модифицировали пакет и расширили таким образом его функциональность или исправили ошибку, вам следует предоставить ваши изменения общественности (некоторые лицензии принуждают вас к этому, кроме того, это считается хорошим тоном).

Перед созданием патча, вы должны скачать самую последнюю версию пакета с CVS. Для этого вам нужно выполнить следующие команды (в примере используется пакет Foo_Bar):
cvs -d:pserver:cvsread@cvs.php.net:/repository login
password is "phpfi"

cvs -z3 -d:pserver:cvsread@cvs.php.net:/repository co Foo_Bar
Теперь у вас есть самая последняя версия исходников и вы можете вносить изменения в соответствующие файлы. Удостоверьтесь, что при написании патча вы учли
Стандарты кодирования PEAR.

После того, как вы закончили добавление/изменение кода - протестируйте его. Мы не примем код, который не был протестирован. Когда будете абсолютно уверены, что ваш код не содержит новых ошибок, создайте унифицированный diff-файл командой:
cd pear/Foo_Bar
cvs diff -u >Foo_Bar.diff
Файл .diff, который получится в результате, содержит ваш патч. С этим diff'ом нам будет значительно проще понять что вы изменили.

Следующий шаг - это предложение патча. Напишите письмо по адресу pear-dev@lists.php.net и пошлите копию (Cc) письма разработчикам пакета. Тема письма должна начинаться с '[Patch]' для того, чтобы было ясно, что вы предлагает патч. Пожалуйста, включите в письмо развернутое объяснение изменений, которые вы предлагаете внести с помощью этого патча. И не забудьте приложить .diff к письму. Разработчики пакеты обычно перечислены в заголовке каждого файла исходников пакета. Кроме этого, их адреса электронной почты можно найти на странице пакета на http://pear.php.net/.

Замечание: Если вы используете Outlook или Outlook Express, пожалуйста, измените расширение файла с .diff на .txt. Определение MIME-типа в Outlook'е зависит от расширения файла и сработает неверно. Письма, содержащие аттачменты, у которых MIME-тип отличается от text/plain будут отвергнуты программным обеспечением рассылки.

Замечание: Если ваш патч ломает обратную совместимость, то очень велики шансы, что разработчики не будут очень рады ему. Поэтому, старайтесь исправлять ошибки так, чтобы не вносить серъезных изменений в API. Но если это абсолютно невозможно и/или ваш патч предоставляет действительно необходимые изменения, то изменения API допустимы.


Сообщения об ошибках

Если вы считаете, что вы нашли ошибку в пакете PEAR - пожалуйста, проверьте, что вы используете последнюю версию пакета и ваша система соответствует требованиям пакета.

Если ошибка все еще проявляется даже с последней версией пакета - не стесняйтесь сообщить о ней по адресу http://bugs.php.net/. При этом вам следует выбрать категорию "PEAR related" для вашего рапорта. Разработчики PEAR будут извещены о вашем рапорте.

Подробная информация и советы по поводу составления рапортов об ошибках могут быть найдены здесь - http://bugs.php.net/how-to-report.php.

Если вы исправили ошибку, которую нашли в пакете - пожалуйста, прочтите это.


Writing & Translating Documentation

Good documentation is essential for users to fully understand any software. Several PEAR packages lack documentation or have docs which need improvement. Writing documentation provides more information about helping out on this front.

Translating documentation is another important task. Not only does new documentation need to be translated into the existing languages, additional languages are welcome. Also, existing translations need to be brought up to date because the English versions have been changed. Help on how to perform the translation process is in the Revision Tracking section of the manual.


Списки пожеланий

Некоторые разработчики PEAR имеют списки пожеланий на сайте Amazon или других подобных сервисах. Если вы хотите отблагодарить конкретного разработчика - вы можете купить ему что-то из его списка пожеланий. Чтобы выяснить есть ли у разработчика такой список, зайдите в список эккаунтов, посмотрите детали разработчика и вы увидите есть ли у него список пожеланий. Покупка предметов из списков иногда может даже увеличить скорость разработки и уменьшить время, за которое исправляются ошибки =)


Глава 6. ЧаВО - Частозадаваемые вопросы


Я написал модуль PHP на C. Что нужно сделать, чтобы он был добавлен в PEAR?

Отвечают Stig Bakken и Martin Jansen.

Если вы хотите сделать обычный модуль, которы не соответствует стандартам кодирования PEAR, то вы можете просто добавить его в pear/PECL/extname (это именно то место, куда будут перемещаться модули из PHP). Если же вы хотите создать модуль, который будет соответствовать соглашениям PEAR, то добавьте его в pear/Foo_Bar, подставив вместо Foo_Bar имя вашего модуля.


Допускаются ли пакеты/классы с похожей функциональностью?

Никаких проблем с конкурирующими пакетами не возникает, однако мы бы хотели избежать появления 10-ти классов шаблонов, 7-ми различных классов по работе с почтой и 3-х врапперов для баз данных, которые будут выполнять одни и те же действия, отличаясь только именами функций.

Для начала, задайте себе вопрос: "Почему я хочу добавить новый пакет?". Самые плохие варианты ответа это: "Хочу увидеть мое имя в списке участников PEAR" и "Я не понимаю API уже существующего пакета".

Обычно, причиной добавления нового пакета является отсутствие функциональности, особенности поведения или проблемы со скоростью/эффективностью у существующего пакета. В этом случае, вы должны удостовериться в том, что расширить или улучшить этот класс/пакет невозможно. Если это действительно так, то вам действительно следует добавить новый пакет. "Действительно невозможно" означает, что нет никакой возможности добавить новую функциональность без изменения основ класса/пакета.

Если вы все-таки решили создать новый класс - старайтесь поддерживать совместимость API со старыми классами настолько, насколько это возможно. Если это невозможно в принципе - попробуйте сделать враппер для поддержания совместимости. И неважно, что этот враппер может требовать значительных ресурсов - так или иначе, но он значительно упростит процесс миграции.

Добавление конкурирующего класса обязательно должно быть согласовано в листе разработчиков PEAR!


У меня есть вопрос, который касается PEAR. Где я могу его задать?

Информация о подписке на эти списки рассылки находится здесь.

Официальным языком всех этих рассылок является английский и постарайтесь быть повежливей =).


Какие лицензии используют пакеты, размещенные в PEAR/PECL?

Отвечают Jan Lehnardt, Tomas V.V. Cox и Rasmus Lerdorf.

Любую из лицензий ПО с открытыми исходниками или свободного ПО. Cм. список лицензий ПО с открытыми исходниками здесь и список лицензий, который были приняты Фондом Свободного ПО - здесь. Выберите любую из этих двух списков. Однако, это не должна быть GPL-совместимая лицензия. Вот примерный список подходящих лицензий: Apache License, Artistic license, BSD license, Common Public License, GPL, IBM Public License, Intel Open Source License, Jabber Open Source License, LGPL, MIT license, Mozilla Public License, PHP License, Python license, Python Software Foundation License, QPL, Sleepycat License, Sun Industry Standards Source License (SISSL), Sun Public License, W3C license, zlib/libpng license, Zope Public license.

Рекомендуется использовать лицензии PHP, LGPL или BSD.

Учтите: если модули из PECL собираются вместе с PHP, то их лицензия должна быть совместима с лицензий PHP. Это означает, что модули PECL с лицензией GPL не могут быть использованы вместе с PHP, т.к. это будет нарушать лицензию GPL. Аналогичная проблема возникает, если ваш модуль использует библиотеку с GPL-лицензией - лицензия будет нарушаться. Если использование такой библиотеки необходимо - попросите разрешения у её автора.

Для того, чтобы распространять пакет из PEAR/PECL под определенной лицензией, добавьте её в начало каждого файла исходного кода, а так же добавьте ее тип в тэг <license> файла описания пакета (package.xml).


Почему стандарт кодирования PEAR настаивает на использовании пробелов вместо табуляций?

Отвечает Stig Bakken.

Использование пробелов вместо табуляций - это единственное решение, которое позволяет быть уверенным в том, что код отображается одинаково во всех редакторах и просмотрщиках. Большое количество редакторов использует длину табуляции, равную 4-м пробелам, но значительно количество терминалов и утилит использует для этого 8 пробелов. Пример:

printf("%s",
      $arg);

Здесь "$arg" предваряют 7 пробелов. Если бы этот код был написан в редакторе с табуляциями из 4-х пробелов, то он был бы сохранен как одна табуляция и три пробела. Теперь представьте себе: другой разработчик редактирует тот же самый файл в редакторе с табуляциями из 8-ми пробелов. Код будет выглядеть так:

printf("%s",
          $arg);

И наоборот:

    if ($foo &&
       $bar) {
   }

В редакторе с табуляциями из 4-х пробелов этот код будет выглядеть так:

    if ($foo &&
   $bar) {
   }

В обществе, подобном PEAR, где состоит большое количество людей, использующих различные системы и редакторы, использование табуляций просто бессмысленно. Участники будут бесконечно изменять файлы для того, чтобы сохранить нормальное форматирование в их редакторе, изменяя его при этом для всех остальных. И только пробелы могут позволить коду выглядеть одинаково везде.

Jamie Zawinski тоже об этом как-то написал, см. здесь.

Существует также утилита Astyle, которая создана для конвертации кода в соответствующий вид.


Is there a tool to help PEAR manual translators to track files changes?

Working on the translations is not just translating an English file and commiting the results. Much of the work is needed to update the already translated ones, to get in sync with the content of the English files. To follow the modifications in the English tree, you should subscribe to the PEAR documentation mailing list to get CVS commit messages, or read the archives. If you never update your files, the translations can get useless.

Updating a foreign language file can get difficult, as you may not know when and who translated that file, so you may not know where you should look for the updates needed. We have one system for tracking the revisions and modification dates of the files in peardoc.


The Revision Comments

Instead of storing all responsibilities in a central file, the revision comment system stores them in the files they provide information about. Information about translator, revision numbers, and status information is stored in the revision comment. Let's see what would be in the header of the example file bookinfo.xml file in this case:
<!-- EN-Revision: 1.16 Maintainer: jane Status: ready -->

We can see the revision number for the last english file used to update the translation (EN-Revision: 1.16), the translator cvs account name. But we can also add some other status information in the case it is needed (eg. "partial" for incomplete translations). This revision comment system is basically about storing the information in the XML files, and not in a central place. This is extremely convenient now, as there are more than 2400 files in the English tree.

Currently, all three fields (English revision, Maintainer, Status) are needed. Maintainer is intended to be a CVS user name, or some nickname without a space, status can be anything without a space. Note, that this header is not updated by CVS (in contrast with $Revision, which is updated automatically). This is only updated when you edit the contents of the comment yourself.

You may see this as a good thing, but using these comments, you lose the quick look on the whole list of your files. No, you do not lose this, but get much more! If you would like to build a full list of you files, you can go to the /peardoc/ directory and run:
./scripts/revcheck_pear.php xx > revcheck.html
Here xx is the imaginary language code. After running this script you'll get a revcheck.html in the same directory. You can find revision comparisions and links to diffs for all the files in this language. You can also add a further restriction parameter, the maintainer name, so the script will only list the files corresponding to the given maintainer.

There are some optional extensions introduced for this script, to be available in this generated HTML page. This is why the translation.xml files are introduced. Here comes a simple translation.xml file for the imaginary xx language :
<?xml version="1.0" encoding="iso-8859-1" ?>
<!DOCTYPE translation SYSTEM "../dtds/translation.dtd">

<translation>

 <intro>
  This is some introductory text for the xx language translators
  about who is the manager of the translation, and where to find
  more information. This paragraph is printed on the top of the
  generated revcheck.html page.
 </intro>
 
 <translators>
  <person name="Joe Doe"     email="joe@hotmail.com"
   nick="joedoe" cvs="yes" editor="yes"/>
  <person name="Jane Smith"  email="jsmith@yahoo.com"
   nick="jane"   cvs="yes"/>
  <person name="Joe Forever" email="joe@forever.net"
   nick="joefo"  cvs="no"/>
 </translators>
 
 <work-in-progress>
  <file name="appendices/aliases.xml" person="joedoe"
   type="working"/>
  <file name="functions/dbx.xml"      person="joefo"
   type="working"/>
 </work-in-progress>

</translation>
In this file, you can add users without a CVS account, and can assign ready documents or work-in-progress files to them. The biggest advantage of using this addon is that all this information is used to generate dynamic tables of translators and files in the revcheck.html file. All translators are linked to from the individual files they are assigned to, and there is a nice table showing the state of files for all the translators. Assigning ready files may be needed if a time consuming update is in progress on that file.

There are two optional parameters you can add to a <file>, if you would like to record it: the date and revision. Date is assumed to be the date when the work was started, revision is the checked out revision of the English file used to start the work (denoted as CO-Revision in the generated table). There is currently no fixed format for the date parameter.

Another addon to this system is just to give credit to all people who worked on one file, and not just the current maintainer. To achieve this goal, we added the credit comments. One credit comment in eg. history.xml may look like this (in case Joe Doe translated the file initially, but Jane followed him to be the maintainer):
<!-- CREDITS: joedoe -->
The credits comment can contain a comma-separated list. These comments only affect the display of the translators table in revcheck.html.


Why does my browser show strange warnings when logging in to the website?

You are seeing the warnings because pear.php.net uses a SSL key that is signed by CAcert, whose root certificate is unfortunately not bundled with most browser.

If you are using a Mozilla browser, you can import the certificate on this site by clicking on the link "Root Certificate (PEM Format)". When asked if you want to trust the new Certificate Authority, you need to check at least the "Trust this CA to identify web sites." box and click "Ok".

People using Internet Explorer may find help here.

Mac OS X users must download the above mentioned PEM file. The certificate can then be imported with the "Keychain Access" utility via "Import" in the "File" menu.


Глава 7. PEAR Group Administrative Documents

One of the jobs of the PEAR Group is to issue administrative documents about diverse topics in PEAR. This chapter contains all of them.


Package Directory Structure

Let's assume we have a package The_Package_Name that contains one or more sub-classes (eg. The_Package_Name_Module), with some documentation (perhaps a README, copies of RFCs, etc.), a battery of test scripts (unit tests, regression tests, etc.), and it uses some data files (localization strings, etc.), the dir tree would look like:

The_Package_Name
|-- Name (contains Module.php)
|-- data
|-- docs
|   `-- examples
|-- misc
|-- scripts
`-- tests

Name refers to the last part of the The_Package_Name, all subclasses of the main class, should be put in there or subdirectories of it. You can refer to http://cvs.php.net/cvs.php/pear/Cache_Lite/ - the directory Lite as an example (this basically documents what we currently do anyway).

The data and misc directories are optional, because it will not make sense to have them for every single package in PEAR.

The directories that are required are docs/examples and tests. A package may have no extra documentation, but it should have at least one example. There must also be some basics test to be able to verify that the package is working. The preferred type of testing script system to use is PHPUnit or .phpt. But for now we would be content with any sort of test script.

Files in scripts will be installed into a directory available in $PATH, such as /usr/local/bin.

Anything that does not fit any of the above categories is placed into the misc directory.

Maintainers are expected to modify their existing packages to match this new standard.


License Announcement

The PEAR Group would like to announce the following refinement of the current license FAQ entry.

Vote result: 5 (+1), 0 (-1), 3 (+0)

The current list allows a great number of licenses which vary greatly. This means that users may have to learn the in's and out's of alot of licenses. Also some of the license choices impose comparitively high restrictions to the standard PHP license (GPL, QPL ..). As PEAR aims to extend the functionality provided by PHP users of PHP should fairly safely be able to also use any PEAR package without licensing worries, be it for commercial or non commercial, closed or opensource use.

Therefore with this announcement the license choices are reduced to the following short list:

  • PHP License

  • Apache License

  • LGPL

  • BSD style

  • MIT License

Other licenses may be accepted on a case by case basis, but will have to fit the above criterias. This decision has been made to simplify the current situation, and as with all decisions is open to be refined in the future using the RFC proposal methodology.

All packages, which are already part of PEAR as of now, which use other licenses, do not need to follow this regulation.

Замечание: In the meantime the FAQ entry linked above has also been updated to reflect the decisions from this document.


New guidelines for BC breaking releases

The goal is to make it possible to be able to run multiple major versions in one script.

For this reason new major versions (BC break or when the maintainer feels it makes sense as a result of dramatic feature additions or rewrites) require a new package using the following naming convention in the following order of preference (where 'Foo' is the package name and 'X' the major version number):

  1. FooX

  2. FoovX

  3. Foo_vX

The choice should be made based on preventing current and future misleading or ambiguous names. This means good care should be taken in making the right choice for the package. Obviously the first two allow for some ambiguity (is DB2 a package for IBM's DB2 or just the major version 2 of DB? - is IPv4 a package for IPv4 or is it the 4th major release if IP?). They don't break the idea of "_" mapping to directories (the class DB_NestedSet implies that there is a nestedset.php in the DB dir). The last one prevents any ambiguity but it's the least visually pleasing and also breaks the '_' to directory mapping and is therefore the last choice.

We also came to the conclusion that the pear installer should not be clever about the relationship between two major releases aside from printing out notices about the fact that there is a newer major version when a user installs an earlier one. However all major versions of a package will be listed on one package home. This is especially important in order to not break tutorials that cover older major releases (tutorial xyz for major version 1 simply says 'pear install Foo' - if the system would then install 'Foo2' the user might be in for an unpleasant surprise).

Therefore, new major versions are for all intents and purposes new packages with the above mentioned exceptions. The names of these new packages are derived using one of the above mentioned naming conventions.


Orphaned Packages

Глоссарий

QA team

Refers to the whole QA team (core and mailing list members)

QA core

Refers to the 6 elected QA team members


Orphaned PEPr Proposals

II. New Maintainers' Guide


Глава 8. Introduction

If you are planning to contribute a new package to the PEAR project, this guide will provide you with the necessary information to get you started The Right Way (tm).

We will start by describing the cases in which it makes sense to contribute and in which not. After we have ensured that the package you want to contribute fits into PEAR, we will describe how to get started with the community. Once you are confident about the inner workings of the PEAR developer community, we will explain how to start the formal process of proposing a new package and we will give some tips for making your first package as successful as possible.


Глава 9. When to contribute (and when not to contribute)

In this chapter we describe the cases in which it makes sense to contribute code to PEAR and in which it does not. This description is by no means complete. If you are unsure, if your contribution could be included into PEAR, contact the developers mailing list.


Cases in which it makes sense to contribute

As you may have already noticed while browsing the list of existing packages, the PEAR packages provide a (often abstract) solution for a general problem. Thus your code will most likely fit into PEAR if it solves a problem that will not only occur in one (e.g. your) specific application, but that occurs in a lot of (web) applications. Examples are:

  • Support for Network protocols

  • Object oriented wrappers that provide easy access to otherwise complicated or less intuitive PHP extensions.

  • Parsing different XML dialects.

    The PEAR packages that provide XML parsing functionalities can be found in the category browser.

No matter which area is covered by a package, the API should be as abstract as possible (while not becoming too complex), so that it can be utilized painlessly in as much use cases as possible.


Глава 10. Getting started with the community

Upon determining your code fits into PEAR, you should get started with the PEAR community. In this chapter we will provide several ways, in which you can establish a first contact with the other PEAR developers, which will hopefully be your future open source fellows. Additionally we will tell you the different places, where you can find more information about the inner workings and rules of PEAR.


Communication with other PEAR developers

Mailing lists naturally are the most important way to communicate in projects like PEAR. We are running a number of public mailing lists, which are listed on the PEAR website. For starters the PEAR developers mailing list pear-dev@lists.php.net is of major importance for you: This mailing list is the place where the maintainers get together to discuss various aspects of their packages and this list is also the place where new packages are discussed.

If you would like to get started with maintaining packages in PEAR, you are expected to be subscribed to this mailing list. (Subscription instructions)

Замечание: During your first steps in the PEAR community, you may stumble across the term "pear-dev", which is the abbreviation for the developers mailing list in PEAR's lingo.

Some people enjoy communicating via IRC channels. We are running the channel #pear in the server network of EFnet. At this channel some of the most active PEAR developers hang out regularly. However for serious inquiries or discussions, you should mail to the developers mailing list.


More written information

  • The PEAR Group occasionally publishes so called Administrative Documents, which describe the Group's decisions. You are expected to read those documents before starting serious contributions to PEAR, because they contain important information about the inner workings of PEAR. The developers mailing list will be informed, when new documents are added, so you do not need to visit the site frequently.

  • This manual contains the Developer Guide, which provides valueable information as well.

  • The Coding Standards describe the standards which PEAR code must adhere to.


Глава 11. The formal proposal process

In the early times of PEAR, all new packages were proposed by an informal email to the PEAR developers mailing list. Over the time, the number of new proposals increased quite dramatically, making it hard to keep track of all the proposals.

A web-based proposal handling system was established to solve these problems. The system is called PEPr. It is pronounced like the spice and stands for "PEAR Proposal system".

This chapter describes the requirements and the workflow for a PEPr-based proposal. After that we will provide you with information, on how to actually start a proposal. Finally, you will learn what to do once the proposal is finished.

After reading this chapter, you will will be able to start a proposal for your code right away.


Step 1: Requirements for a proposal

The following enumeration lists the most important things that need to be done or be made available before starting a new proposal.


Step 2: Initiating a discussion

For every package you should start a proposal in PEPr as a draft to initiate dicussion on the developers mailing list.

By discussing the package with the PEAR developers you will easily be able to find out if:

  • there are technical issues with the package/code

  • a package with similar functionality already exists

  • there are people working on something similar, so you can join forces

  • etc.

By reading between the lines, you should also be able to find out if you will be able to gather enough positive votes in the formal proposal process.

Be aware that people will scrutinize your code, so be prepared for criticism (both positive and negative) and save everybody a bunch of time by making sure your scripts adhere to the Coding Standards.

Please note that PEAR is an international project. People come from different cultural backgrounds where english may not be their native tongue. Misunderstandings may happen because of that, so assume the person is trying to do good. Do not worry if your English is not perfect but do try to be as clear as possible and do not hesitate to ask for advice.


Step 3: Using PEPr

To be able to use the proposal tool (PEPr), you have to apply for a PEAR website account. This account will usually be granted within one or two days. After that you can open a new proposal using the "New Package Proposal" interface.

The package proposal process is divided into 4 stages: "Draft", "Proposal", "Call for Votes" and "Finished". Every proposal has to run through all of these stages. During each stage (except for the draft stage) an email is send to you (the proposer) and the PEAR developers mailing list for any action.


Changing a proposal

In general you may not edit or delete your proposal after it has left the Proposal stage. In urgent cases you can contact the PEAR community via the developers mailing list to reach a PEAR website administrator to do a change. This is heavily discouraged however! You should have made everything clear to the community during the Proposal stage to ensure a hassle free voting process. Even if the voting has a negative result, this is no reason to delete it.


Глава 12. Taking over an unmaintained package

If you want to become the new lead maintainer of a package that is marked as unmaintained on the PEAR website, the following section will explain to you the necessary steps for this to happen.

  1. The first thing is to inform the PEAR Quality Assurance mailing list about your intention. If you have not been involved in PEAR prior to that, it is a good idea to write a few words about you and your motivations.

  2. The QA team will then state whether you can take over the package or not, eventually explaining why. You can then apply for an account for the PEAR website unless you already have one. The PEAR Group will have to grant this account, and afterwards the QA team will assign you as the new lead maintainer for the package.

  3. If the sources of the package are kept in the PHP CVS repository, you will also need an account for this. You can sign up for it on the PHP website. Please mention in the purpose field of the request form that the PEAR QA team has told you to get an account, so that your request can be processed faster. CVS accounts are managed by the PHP Group, so PEAR unfortunately has only limited influence on this process.

    Замечание: In case you already have a CVS account for cvs.php.net, it is only necessary for you to get additional "karma" for the module where the package resides. You can request this karma by sending an email to the PEAR Group. (Please also mention in this mail that you have already talked to the QA team.)

  4. If everything has worked out well, you should by now be the lead maintainer of the previously unmaintained package. If not, don't hesitate to ask the people on the QA mailing list for help.

III. Руководство разработчика


Глава 14. Значение PEAR для разработчиков


Код высокого качества

PEAR состоит из кода только высокого качества, который соответствует стандартам кодирования PEAR. Для вас это значит, то вы используете код с cоответствующим API, который основан на стандартных компонентах и который использует один и тот же механизм управления ошибками везде.

Учтите, что это не относится к коду, который находится в PECL: в PECL весь код соответствует стандартам кодирования PHP.


Глава 15. Добавление вашего кода


Требования к новому коду

Есть несколько требований, которые должны соблюдаться для того, чтобы ваш код был добавлен в PEAR:

  1. Соответствие стандартам кодирования

    Если вы хотите добавить ваш код в PEAR, то он обязательно должен соответствовать стандартам кодирования. В свое время, после множества дискуссий о том, нужны стандарты или нет, было принято решение - необходимы. Пожалуйста, не пытайтесь продолжить споры на эту тему.

  2. Должна быть возможность расширения кода и добавления новой функциональности ("forward-compatible" code).

    Помните: ваш код должен легко расширяться, добавление новой функциональности не должно вызывать никаких проблем. Если у вас никак не получается сделать подобный код без изменения принципов работы кода, то вам, видимо, еще рано добавлять код в PEAR, попробуйте перепроектировать код.

  3. Документация в соответствующих форматах (plain text, docbook)

    Ваш код должен поставляться с соответствующей документацией в одном из следующих форматов:

    Если вы создадите документацию в формате Docbook XML и разметка будет соответствовать всем правилам, то документация будет сразу же добавлена в официальное справочное руководство по PEAR, которое вы читаете в данный момент.

    Замечание: Существуют планы реализовать автоматическую систему конвертации формата phpDocumentor в формат Docbook XML, который уже будет добавляться в официальное руководство автоматически. Но пока вам придется писать документацию вручную.

  4. Автор кода ("вы") должен иметь желание и возможность поддерживать в будущем свой пакет (или пакеты) и выпускать новые версии для исправления ошибок.

    Если у вас нет желания поддерживать ваш код, это значит, что добавлять его в PEAR нет смысла. Поддержка кода - это в первую очередь оказание помощи другим разработчикам, которые используют ваш пакет, в основном с помощью листов рассылки, а также выпуск новых релизов кода, исправление ошибок и улучшение функциональности.

    Внимание

    Код может быть удален из PEAR, если его автор не желает более заниматься его поддержкой и никто другой такого желания не проявляет.


Как добавить свой код в PEAR

  1. Присвоение новому пакету правильного имени

    Одна из самых важных задач при добавлении вашего кода в PEAR - это нахождение наиболее подходящего имени для вашего пакета.

    Общие правила наименования пакетов таковы: <Категория>_<Имя>. Имя <Категории> должно быть выбрано из уже существуеющего списка категорий PEAR (например, "HTTP", "Net", "HTML"). Вторая часть имени - это имя самого пакета (например, "Upload", "Portscan", "Table").

    Если вы считаете, что ваш пакет не подходит ни к одной из существующих категорий, вы можете попросить создать новую. Однако, мы стараемся сохранить как можно более простую структуру категорий.

    В качестве исключений из общих правил, имя пакета может содержать более одного имени категории. Например, пакет HTML_Template_PHPLIB : множество категорий в имени пакет означает, что пакет PHPLIB является частью категории Template, которая, в свою очередь, принадлежит к категории HTML. В данном случае имя формируется именно по такому принципу потому, что в PEAR могут существовать шаблонные системы, которые не будут работать с HTML, а будут предназначены для использования с другими технологиями.

    Если вы хотите получить совет или нуждаетесь в помощи при выборе имени пакета - спросите в листе разработчиков.

  2. Представление кода разработчикам PEAR

    Второй шаг, который вам необходимо выполнить для добавления вашего пакета в PEAR - это представление пакета в рассылке разработчиков. Обычно такое представление вызывает порождает обсуждение и небольшое голосование, в котором разработчики будут отдавать свои голоса "за" или "против" вашего предложения. Конечно, вам стоит поучаствовать в этой дискуссии. Получение от разработчика "+1" означает, что ему нравится ваше предложение, получение "-1" - наоборот, это голос "против". При получении более пяти "+1" вы можете перейти к следующему шагу.

  3. Получение эккаунтов

    На данный момент можно отличить два вида эккаунтов, которые относятся к PEAR:

    1. учетная запись Pear.php.net

      Эта учетная запись нужна вам для того, чтобы вы могли добавлять релизы вашего пакета. С этим эккаунтом вы сможете получить доступ к необходимым страницам на pear.php.net для загрузки новых релизов.

    2. учетная запись на сервере CVS

      Если вы хотите управлять вашим кодом с помощью CVS, то вы можете получить эккаунт на CVS для получения доступа к модулю pear на cvs.php.net. Это значительно облегчит участие других разработчиков в разработке вашего пакета.

      Если у вас уже есть репозиторий CVS где-то в другом месте (например, на SourceForge) или вы не хотите управлять своим кодом с помощью CVS, то CVS-эккаунт вам не нужен.

    Для того, чтобы получить эккаунт на pear.php.net, зайдите на страницу запроса эккаунта в PEAR и заполните форму. Администраторы PEAR получат ваш запрос и создадут вам учетную запись, если найдут причины для этого достаточными. Вам сообщат о конечном результате по е-мэйлу. Учтите, что вам не нужен эккаунт для того, чтобы загружать себе пакеты с pear.php.net.

    Для того, чтобы получить CVS-эккаунт, зайдите сюда и заполните соответствующие поля. Вопрос о создании вам эккаунта будет решаться участниками PHP Group.

  4. Процедура выпуска релизов

    Для начала, чтобы получить возможность добавить ваш пакет в PEAR, вы должны получить эккаунт на pear.php.net.

    Перед выпуском первого релиза вашего пакета, вам следует зарегистрировать сам пакет. Для этого вы должны зайти сюда и заполнить соответствующие поля формы. Пожалуйста, выбирайте имя пакета, которое будет соответстовать пункту первому этой главы.

    После регистрации пакета, вы сможете выпустить первую версию пакета.

    Перед этим необходимо создать файл описания пакета. Этот файл в формате XML, с именем package.xml должен находиться в корневой директории исходников пакета.

    Дополнительная информация о файлах описаний пакетов находится здесь.

    После того, как вы создали этот файл, запустите
    
         $ pear package
            
    в корневой директории пакета. Эта команда создаст файл .tgz в той же директории. В нашем примере это будет файл с именем Money_Fast-1.0.tgz.

    Теперь заходите на эту страницу и загружайте tgz-файл на сервер. После этого выпуск версии 1.0 пакета уже можно считать состоявшимся.


Глава 16. Файл описания пакета - package.xml


Введение

Файл описания пакета, package.xml, как становится понятно из его имени - это XML-файл, который содержит всю информацию о пакете из PEAR.

В этой главе описываются элементы, которые могут присутствовать в файле описания пакета, а также обсуждаются способы создания такого файла для вашего пакета.


Допустимые элементы

Корневым элементом файла package.xml является элемент <package version="1.0">. Допускаются следующие вложенные элементы:

  • <name>: Имя пакета.

  • <summary>: Краткое описание пакета.

  • <description>: Полное описание пакета.

  • <license>: Лицензия (PHP License, LGPL и т.п.). Более подробная информация о допустимых лицензиях в PEAR содержится в FAQ.

  • <maintainers>: Информация о создателях пакета.

    • <maintainer>: Информация о каждом создателе отдельно (может присутствовать несколько раз, для каждого разработчика).

      • <user>: Имя аккаунта разработчика.

      • <role>: Роль разработчика в процессе создания пакета. Может принимать значения: lead, developer, contributor, helper.)

      • <name>: Настоящее имя разработчика.

      • <email>: Адрес электронной почты.

  • <release>: Информация о текущем релизе.

    • <version>: Номер версии релиза.

    • <state>: Статус релиза. (Может быть alpha, beta, stable, devel или snapshot)

    • <date>: Дата релиза.

    • <notes>: Комментарии к релизу

    • <filelist>

      • <file role="xxx">: Имя файла

      • <dir name="xxx" [role="xxx"]>: Имя поддиректории. Поддиректория, в свою очередь, может содержать другие элементы <file role="xxx">.

    • <deps>: Список зависимостей пакета.

      • <dep type="xxx" rel="yyy" optional="yes">name</dep> : Более подробную информацию о зависимостях можно найти ниже.

  • <changelog>: Changelog(история изменений) пакета.

    • <release>

      • <version>: Версия конкретного релиза.

      • <state>: Статус конкретного релиза.

      • <date>: Дата конкретного релиза.

      • <notes>: Комментарии к релизу.


Создание файла описания пакета

Этот файл package.xml может послужить вам шаблоном, т.к. он уже содержит все необходимые поля. В большинстве случаев, вам нужно будет всего лишь поменять текст между тэгами, чтобы использовать пример в вашем пакете.

В этом примере демонстрируется очень удобный прием: когда в какой-то из ваших директорий содержатся файлы только одного типа, вы можете использовать атрибут "role" у элемента <dir> вместо того, чтобы добавлять его у каждому элементу <file>.

После прочтения данной главы вы уже можете создавать файл описания пакета. Если у вас все еще есть вопросы по этому поводу - задавайте их в листе рассылки.


Определение зависимостей

PEAR Package Manager или менеджер пакетов позволяет задавать различные требования к системе. Вы можете определить зависимости от этих требований с помощью элемента <dep>:


Атрибут rel

Атрибут rel определяет отношение между существующей возможностью и требованием.

Has используется, если не определено других значений. Стоит отметить, что rel обязателен для PEAR 1.4.0 и выше.


Глава 17. The package definition file package.xml, version 2.0


A quick and dirty guide to version 2.0 of the package definition file package.xml

The package definition file package.xml is, as the name already implies, a well-formed XML file that contains all information about a PEAR package. Version 2.0 contains several important enhancements over version 1.0, including

For those of you with an existing package.xml version 1.0, you can create an approximate equivalent package using the


$ pear convert
     

command. Note that as of version 1.6.0a1, PEAR_PackageFileManager supports package.xml 2.0 with the PEAR_PackageFileManager2 class.

PECL developers: for more information on pecl-specific features, read here.


An example file with all elements

<?xml version="1.0"?>
<package version="2.0" xmlns="http://pear.php.net/dtd/package-2.0"
    xmlns:tasks="http://pear.php.net/dtd/tasks-1.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://pear.php.net/dtd/tasks-1.0
http://pear.php.net/dtd/tasks-1.0.xsd
http://pear.php.net/dtd/package-2.0
http://pear.php.net/dtd/package-2.0.xsd">
 <name>PEAR</name>
 <channel>pear.php.net</channel>
 <summary>Any one-line summary</summary>
 <description>any static long description.
 This text should not change very much between releases, use the "notes" tag
 for release notes
 </description>
 <lead>
  <name>Greg Beaver</name>
  <user>cellog</user>
  <email>cellog@php.net</email>
  <active>yes</active>
 </lead>
 <date>2005-02-26</date>
 <time>20:30:13</time> <-- note: <time> is optional -->
 <version>
  <release>1.4.0a2</release>
  <api>1.4.0</api>
 </version>
 <stability>
  <release>alpha</release>
  <api>alpha</api>
 </stability>
 <license uri="http://www.php.net/license">PHP License</license>
 <notes>
 Put release notes here.
 They can be multi-line
 </notes>
 <contents>
  <dir name="/">
   <dir name="PEAR">
    <dir name="ChannelFile">
     <file name="Parser.php" role="php" />
    </dir> <!-- /PEAR/ChannelFile -->
    <file name="Dependency2.php" role="php">
     <tasks:replace from="@PEAR-VER@" to="version" type="package-info"/>
    </file>
   </dir> <!-- /PEAR -->
   <dir name="scripts" baseinstalldir="/">
    <file name="pear.bat" role="script">
     <tasks:replace from="@bin_dir@" to="bin_dir" type="pear-config" />
     <tasks:replace from="@php_bin@" to="php_bin" type="pear-config" />
     <tasks:replace from="@include_path@" to="php_dir" type="pear-config" />
     <tasks:windowseol/>
    </file>
    <file name="pecl.bat" role="script">
     <tasks:replace from="@bin_dir@" to="bin_dir" type="pear-config" />
     <tasks:replace from="@php_bin@" to="php_bin" type="pear-config" />
     <tasks:replace from="@include_path@" to="php_dir" type="pear-config" />
     <tasks:windowseol/>
    </file>
    <file name="pear.sh" role="script">
     <tasks:replace from="@php_bin@" to="php_bin" type="pear-config" />
     <tasks:replace from="@php_dir@" to="php_dir" type="pear-config" />
     <tasks:replace from="@pear_version@" to="version" type="package-info" />
     <tasks:replace from="@include_path@" to="php_dir" type="pear-config" />
     <tasks:unixeol/>
    </file>
    <file name="pecl.sh" role="script">
     <tasks:replace from="@php_bin@" to="php_bin" type="pear-config" />
     <tasks:replace from="@php_dir@" to="php_dir" type="pear-config" />
     <tasks:replace from="@pear_version@" to="version" type="package-info" />
     <tasks:replace from="@include_path@" to="php_dir" type="pear-config" />
     <tasks:unixeol/>
    </file>
    <file name="pearcmd.php" role="php">
     <tasks:replace from="@php_bin@" to="php_bin" type="pear-config" />
     <tasks:replace from="@php_dir@" to="php_dir" type="pear-config" />
     <tasks:replace from="@pear_version@" to="version" type="package-info" />
     <tasks:replace from="@include_path@" to="php_dir" type="pear-config" />
    </file>
    <file name="peclcmd.php" role="php">
     <tasks:replace from="@php_bin@" to="php_bin" type="pear-config" />
     <tasks:replace from="@php_dir@" to="php_dir" type="pear-config" />
     <tasks:replace from="@pear_version@" to="version" type="package-info" />
     <tasks:replace from="@include_path@" to="php_dir" type="pear-config" />
     <tasks:footask/>
    </file>
   </dir> <!-- /scripts -->
   <file name="package.dtd" role="data" />
   <file name="postinstall.php" role="php">
    <tasks:postinstallscript/>
   </file>
   <file name="template.spec" role="foo" />
  </dir> <!-- / -->
 </contents>
 <compatible>
  <name>FooPackage</name>
  <channel>pear.php.net</channel>
  <min>1.3.0</min>
  <max>1.5.0</max>
 </compatible>
 <dependencies>
  <required>
   <php>
    <min>4.2</min>
    <max>6.0.0</max>
   </php>
   <pearinstaller>
    <min>1.4.0dev13</min>
   </pearinstaller>
   <package>
    <name>Archive_Tar</name>
    <channel>pear.php.net</channel>
    <min>1.1</min>
    <recommended>1.2</recommended>
   </package>
   <package>
    <name>Foo</name>
    <uri>http://www.example.com/Foo-1.2.0.tgz</uri>
   </package>
   <extension>
    <name>xml</name>
   </extension>
   <os>
    <name>windows</name>
    <conflicts/>
   </os>
   <arch>
    <pattern>*-i?86-*-*</pattern>
   </arch>
  </required>
  <optional>
   <package>
    <name>PEAR_Frontend_Web</name>
    <channel>pear.php.net</channel>
    <min>0.5.0</min>
   </package>
   <package>
    <name>PEAR_Frontend_Gtk</name>
    <channel>pear.php.net</channel>
    <min>0.4.0</min>
   </package>
  </optional>
  <group name="remoteinstall" hint="adds the ability to install packages to a remote ftp server">
   <package>
    <name>Net_FTP</name>
    <channel>pear.php.net</channel>
    <min>1.3.0RC1</min>
    <recommended>1.3.0</recommended>
   </package>
  </group>
  <group name="webinstaller" hint="PEAR's web-based installer">
   <package>
    <name>PEAR_Frontend_Web</name>
    <channel>pear.php.net</channel>
    <min>0.5.0</min>
   </package>
  </group>
  <group name="gtkinstaller" hint="PEAR's PHP-GTK-based installer">
   <package>
    <name>PEAR_Frontend_Gtk</name>
    <channel>pear.php.net</channel>
    <min>0.4.0</min>
   </package>
  </group>
 </dependencies>
 <usesrole>
  <role>foo</role>
  <package>Foo</package>
  <channel>pear.example.com</channel>
 </usesrole>
 <usestask>
  <task>footask</task>
  <package>Footask</package>
  <channel>pear.example.com</channel>
 </usestask>
 <phprelease>
  <installconditions>
   <os>
    <name>windows</name>
   </os>
  </installconditions>
  <filelist>
   <install as="pear.bat" name="scripts/pear.bat" />
   <install as="pecl.bat" name="scripts/pecl.bat" />
   <install as="pearcmd.php" name="scripts/pearcmd.php" />
   <install as="peclcmd.php" name="scripts/peclcmd.php" />
   <ignore name="scripts/pear.sh" />
   <ignore name="scripts/pecl.sh" />
  </filelist>
 </phprelease>
 <phprelease>
  <filelist>
   <install as="pear" name="scripts/pear.sh" />
   <install as="pecl" name="scripts/pecl.sh" />
   <install as="pearcmd.php" name="scripts/pearcmd.php" />
   <install as="peclcmd.php" name="scripts/peclcmd.php" />
   <ignore name="scripts/pear.bat" />
   <ignore name="scripts/pecl.bat" />
  </filelist>
 </phprelease>
 <changelog>
  <release>
   <version>
    <release>1.3.5</release>
    <api>1.3.0</api>
   </version>
   <stability>
    <release>stable</release>
    <api>stable</api>
   </stability>
   <date>2005-02-26</date>
   <license uri="http://www.php.net/license/3_0.txt">PHP License</license>
   <notes>
 * fix Bug #3505: pecl can't install PDO
 * enhance pear run-tests dramatically
 * fix Bug #3506: pear install should export the pear version into the environment

   </notes>
  </release>
  <release>
   <version>
    <release>1.4.0a1</release>
    <api>1.4.0</api>
   </version>
   <stability>
    <release>alpha</release>
    <api>alpha</api>
   </stability>
   <date>2005-02-26</date>
   <license uri="http://www.php.net/license/3_0.txt">PHP License</license>
   <notes>
  This is a major milestone release for PEAR.  In addition to several killer features,
  every single element of PEAR has a regression test, and so stability is much higher
  than any previous PEAR release, even with the alpha label.

  New features in a nutshell:
  * full support for channels
  * pre-download dependency validation
  * new package.xml 2.0 format allows tremendous flexibility while maintaining BC
  * support for optional dependency groups and limited support for sub-packaging
  * robust dependency support
  * full dependency validation on uninstall
  * support for binary PECL packages
  * remote install for hosts with only ftp access - no more problems with
    restricted host installation
  * full support for mirroring
  * support for bundling several packages into a single tarball
  * support for static dependencies on a url-based package

  Specific changes from 1.3.5:
  * Implement request #1789: SSL support for xml-rpc and download
  * Everything above here that you just read
   </notes>
  </release>
 </changelog>
</package>


Special information for PECL developers

extsrcrelease and extbinrelease changes for PECL developers

extsrcrelease and extbinrelease changes for PECL developers -- PECL-specific details of package.xml 2.0

Detailed Tag Reference for package.xml version 2.0

Содержание
<channel> -- What is a channel?
<uri> -- When should I use <uri>?
<lead>, <developer>, <contributor>, and <helper> -- Developer documentation for a release
<version> -- versioning in package.xml 2.0
<stability> -- specifying release and API stability
<license> -- specifying software license and optional reference to license text
<contents> -- specifying the contents of a release
<dir> -- documenting a directory in the <contents> tag
<file> -- documenting a file in the <contents> tag
tasks for <file>s -- specialized file installation and manipulation
<compatible> -- Alleviating strict versioning with <compatible>
<dependencies> -- Dependency Specification in package.xml 2.0
<usesrole> -- documenting custom file roles used in <contents>
<usestask> -- documenting custom tasks used in <contents>
<phprelease>, <extbinrelease>, <extsrcrelease>, <bundle> -- specifying the content type of a release

Each tag that needs further explanation is documented here (unfinished)

<channel>

<channel> -- What is a channel?

Quick introduction to channels

Channels are new in PEAR 1.4.0. Channels are a systemized way of differentiating between different download sources. One such download source is pear.php.net, another is pecl.php.net, and there are several third party channels slowly springing up around the net.

The <channel> tag should contain the full channel name, not any alias (don't use "pear", use "pear.php.net".

A good rule of thumb to use when determining what channel name to use is "where do I upload my releases to?" If the answer is pear.php.net, that is your package's channel. If the answer is pecl.php.net, then that is your channel.

If you aren't running a channel server and wish to serve your packages as well as allow other packages to remotely depend on your package, the new uri-based package distribution method is the best choice, see the <uri> tag documentation link below.

See also:

<uri>

<uri>

<uri> -- When should I use <uri>?

When to use <uri> instead of <channel>

If you do not have a channel server and wish to serve your packages so that others can depend on them, use <uri>. This should contain a static uri that links to a single package version's downloadable .tgz

If you do not need to allow external remote dependencies, then simply use the pear.php.net channel as your package's channel.

For instance, if you wish to serve package Foo version 1.1.0 from www.example.com, use the uri "http://www.example.com/Foo-1.1.0". Note that the uri must contain the full path MINUS THE EXTENSION. Provide both Foo-1.1.0.tgz and Foo-1.1.0.tar for users without gzip.

See also:

<channel>

<lead>, <developer>, <contributor>, and <helper>

<lead>, <developer>, <contributor>, and <helper> -- Developer documentation for a release

Documenting who develops a package

In package.xml 1.0, a developer was documented using the <maintainer> tag inside of a redundant <maintainers> container tag. This has been simplified in package.xml 2.0 both to slightly speed parsing and to make validation of the xml simpler. Now, the contents of the <role> tag has been extracted as 4 tags to describe the maintainers of a package.

In addition, a new internal tag <active> has been added, so that you can honor retired developers' work without having to remove them altogether from package.xml.

WARNING: tag order is important. List leads followed by developers followed by contributors and finally helpers.

<version>

<version> -- versioning in package.xml 2.0

Documenting release version and API version

In package.xml 1.0, the version was simply the version. package.xml 2.0 splits the concept of versioning into two components, release and api.

The release version is the same familiar versioning concept from package.xml 1.0. This version is validated very carefully by the packager.

The API version is informational only - the installer does not use it. It can be used for a package-time replacement by the installer. This can be very useful when implementing a reflective method such as getApiVersion(). In addition, the API version is very loosely validated, and only requires a version_compare()-compatible version number.

<stability>

<stability> -- specifying release and API stability

Documenting release stability and API stability

In package.xml 1.0, stability was known as "state" which is not the most accurate description. package.xml 2.0 introduces the term stability and like version splits the concept of stability into two components, release and api.

The release stability is the same familiar state from package.xml 1.0. It can be one of:

  1. snapshot - a frozen picture of development at a particular moment

  2. devel - a very new non-production release. Devel should be used for extremely new, practically untested code.

  3. alpha - a new non-production release. Alpha should be used for new code that has an unstable API or untested code.

  4. beta - a non-production release. Beta should be used for code that has a stable API and is nearing a fully stable release. Regresion tests and documentation should exist or soon follow to qualify as a beta release. Release candidates should use the beta stability.

  5. stable - a production release. Stable releases must have a stable API, and must have regression tests and documentation.

The API stability is informational only - the installer does not use it.

<license>

<license> -- specifying software license and optional reference to license text

Documenting release license

In package.xml 1.0, the license tag only contained the name of the license. In package.xml 2.0, there are two optional attributes, "uri" and "filesource". "uri" contains a uri that identifies the text of a license, such as "http://www.php.net/license" for the PHP License. "filesource" can be used to specify a LICENSE file within an actual package that contains the text of the license.

<contents>

<contents> -- specifying the contents of a release

Documenting release contents

In package.xml 1.0, the contents tag was <filelist>. The purpose of the tag changed dramatically in package.xml 2.0, warranting a name change. Now, <filelist> can be found in the release section of the package.xml.

<contents> is used to describe the contents of a tarball. Nothing further. All files in the contents tag will be placed into the tarball regardless of whether they eventually get installed by the PEAR installer. This fact can be used to create a very versatile tarball, one that can be directly unzipped and work out of the box as well as be installed by the PEAR installer and work out of the box.

For most release types, contents contains a single <dir> tag that then either contains nested dir tags and/or <file> tags.

<dir>

<dir> -- documenting a directory in the <contents> tag

Documenting directories

The <dir> tag is identical to package.xml 1.0. Required attributes are name and optional attributes are baseinstalldir (the relative location where all files and subdirectories will be installed)

Note that all files must be contained in a single top-level <dir> tag. For simple packages, simply use <dir name="/"> as the directory name

<file>

<file> -- documenting a file in the <contents> tag

Documenting files

The <file> tag is almost identical to package.xml 1.0. Required attributes are name and role. Optional attributes are baseinstalldir and md5sum. Optional attributes platform and install-as have been replaced by the release tags. Specifically, <install> is used to specify install-as, and the <ignore> tag can be used in conjunction with <installconditions> to exclude packages from being installed on particular platforms.

For those familiar with the platform attribute, the way to handle this example:

<file name="scripts/foo.bat" role="script" install-as="foo.bat" platform="windows">

is to in fact create two release sections. The file tag would then look like:

<file name="scripts/foo.bat" role="script">

and the release section would look like this:

<phprelease> <installconditions> <os>windows</os> </installconditions> <install name="scripts/foo.bat" as="foo.bat"/> </phprelease> <phprelease> <ignore name="scripts/foo.bat"/> </phprelease>

Note that the second <phprelease> tag could just as easily have had an <installconditions> tag containing <os>unix</os>, but this is unnecessary, as the second release will be processed on any system that is not a windows system.

tasks for <file>s

tasks for <file>s -- specialized file installation and manipulation

Using tasks to customize file installation

Tasks provide a flexible and customizable way to manipulate file contents or to perform complex installation tasks (hence the name "tasks"). By default, PEAR comes with 4 tasks, but customized tasks can be added simply by adding a file into the PEAR/Tasks directory that follows the conventions of existing tasks. This page does not describe how to create a custom task, only how to use them in package.xml.

There are 3 basic tasks and 1 complex task distributed with PEAR. The basic tasks are "tasks:replace", "tasks:windowseol", and "tasks:unixeol". The complex task is "tasks:postinstallscript". "tasks:replace" is nearly identical to the old <replace> tag from package.xml 1.0, and does a text search-and-replace of a file's contents. "tasks:windowseol" and "tasks:unixeol" manipulate the line endings of a file to ensure that the correct line endings are in place for critical files like DOS .bat batch files and unix shell scripts. "tasks:postinstallscript" allows users to choose to run a script to perform further installation functions.

<tasks:replace> - customizing file contents

The replace task has 3 required attributes:

  1. type - This must be either package-info or pear-config. package-info replacements extract information from package.xml itself to use as the replacement text. pear-config replacements use the value of a configuration variable (as displayed by
    pear config-show
    ) as the text for replacement.

  2. from - Text to search for in a file. Traditionally, this text is enclosed in "@" to differentiate it from normal text, as in from="@version@"

  3. to - Abstract item to use as a replacement for all occurences of "from". package-info replacements can be one of version, release_date, release_state, release_license, release_notes, apiversion, name, summary, description, notes, time, date, and for some packages extends, srcpackage, srcuri, and providesextension.

Note that package-info replacements are performed at packaging time, so files contain package-info replacements inside a .tgz/.tar release. pear-config replacements can only occur on the installation system, and are performed at install-time.

<tasks:windowseol> - converting line endings to \r\n

This task can be used to enable packaging of windows-specific files (like DOS batch files) on a non-windows system, such as unix systems that convert line endings to \n. Note that this task is performed at package-time, as well as at install-time, so files will contain the correct line endings inside a .tgz/.tar release.

<tasks:unixeol> - converting line endings to \n

This task can be used to enable packaging of unix-specific files (like sh shell scripts) on a non-unix system, such as windows systems that convert line endings to \r\n. Note that this task is performed at package-time, as well as at install-time, so files will contain the correct line endings inside a .tgz/.tar release.

<tasks:postinstallscript> - extreme customization

The postinstallscript task informs the installer that the file it references is a post-installation script.

For security reasons, post-install scripts must be manually executed by the users, and as such the installer has special code that is separate from other tasks.

The <postinstallscript> tag may define parameters that are used by the installer to retrieve user input. In order to support both the web installer and the command-line installer, all processing of input is performed by PEAR and passed to the post-install script in a strict format. All you need to do is define the parameters using xml inside the <postinstallscript> tag.

Here is the xml representing a simple post-install script with parameters:

<tasks:postinstallscript>
 <tasks:paramgroup>
  <tasks:id>first</tasks:id>
  <tasks:param>
   <tasks:name>test</tasks:name>
   <tasks:prompt>Testing Thingy</tasks:prompt>
   <tasks:type>string</tasks:type>
  </tasks:param>
 </tasks:paramgroup>
</tasks:postinstallscript>

Note that the only type recognized at this stage is "string" but others will follow. A more complex example follows:

<tasks:postinstallscript>
 <tasks:paramgroup>
  <tasks:id>first</tasks:id>
  <tasks:instructions>The first group of questions relates
   primarily to your favorite color.  Answer wisely.
  </tasks:instructions>
  <tasks:param>
   <tasks:name>test</tasks:name>
   <tasks:prompt>Testing Thingy</tasks:prompt>
   <tasks:type>string</tasks:type>
   <tasks:default>hi</tasks:default>
  </tasks:param>
  <tasks:param>
   <tasks:name>test2</tasks:name>
   <tasks:prompt>Testing Thingy 2</tasks:prompt>
   <tasks:type>string</tasks:type>
  </tasks:param>
 </tasks:paramgroup>
 <tasks:paramgroup>
  <tasks:id>second</tasks:id>
  <tasks:name>first::test</tasks:name>
  <tasks:conditiontype>preg_match</tasks:conditiontype>
  <tasks:value>g+</tasks:value>
  <tasks:param>
   <tasks:name>test</tasks:name>
   <tasks:prompt>Testing Thingy a</tasks:prompt>
   <tasks:type>string</tasks:type>
   <tasks:default>hi</tasks:default>
  </tasks:param>
  <tasks:param>
   <tasks:name>test2</tasks:name>
   <tasks:prompt>Testing Thingy b</tasks:prompt>
   <tasks:type>string</tasks:type>
  </tasks:param>
 </tasks:paramgroup>
</tasks:postinstallscript>

This post-installation script has two parameter groups. The first parameter group has special instructions that are displayed to the user to assist in answering the required prompts. After the first group is processed, the second group is processed (naturally). However, in this case, the second group is a conditional parameter group. A conditional parameter group examines the user input from previous parameter groups and only displays its parameter prompts if a single parameter fits a test. The condition is defined by three tags, <tasks:name>, <tasks:conditiontype>, and <tasks:value>. Note that all three tags are required or xml validation will fail.

<tasks:name> is the parameter name from a previous parameter group. The format of name is groupID::parameterName, so as you see above, "first::test" refers to the <tasks:param> test from the <tasks:paramgroup> first.

<tasks:conditiontype> determines how the parameter input function will process the value of the parameter specified in <tasks:name>, and can be one of three values, "=" "!=" or "preg_match".

  • =: This (obviously) tests whether the parameters value is equal to the <tasks:value> tag

  • !=: This (obviously) tests whether the parameters value is not equal to the <tasks:value> tag

  • preg_match: This uses the content of the <tasks:value> tag as if it were the stuff between / and / in a preg_match() function call. Do NOT include // brackets in the regular expression. In the <tasks:paramgroup> second, the value "g+" will become:
    <?php
    preg_match('/g+/', first::test value)
    ?>

<compatible>

<compatible> -- Alleviating strict versioning with <compatible>

Working with <recommended> dependency versions and <compatible>

The <compatible> tag is designed to be used with a <package> dependency that contains a <recommended> version tag from package pear.example.com/Bar version 1.3.0 like so:

<package>
 <name>Foo</name>
 <channel>pear.example.com</channel>
 <min>1.0.0</min>
 <recommended>1.5.2</recommended>
</package>

The above dependency can be translated into English as follows: "Use the package pear.example.com/Foo, but only versions 1.0.0 or newer. If pear.example.com/Foo is not installed, install version 1.5.2. If pear.example.com/Foo is installed and is not version 1.5.2, fail unless --force is specified, or pear.example.com/Foo is compatible with me."

That last clause "...or pear.example.com/Foo is compatible with me." is controlled by the <compatible> tag. If package Foo version 1.5.3's package.xml has a <compatible> like so:

<compatible>
 <name>Bar</name>
 <channel>pear.example.com</channel>
 <min>1.2.0</min>
 <max>1.3.0</max>
 <exclude>1.2.9</exclude>
</compatible>

This will instruct the installer that pear.example.com/Foo version 1.5.3 is compatible with pear.example.com/Bar versions 1.2.0 to 1.3.0 inclusive, but is not compatible with 1.2.9.

It is very important to note that only existing versions that have been tested with the package should be mentioned in the <compatible> tag. Future versions of pear.example.com/Bar should simply upgrade the <recommended> tag.

<compatible> may contain three versioning tags. The required <min> and <max> are used to define the range of tested and compatible versions, and <exclude> is used to exclude any versions within the range. In the example above, 1.3.0 and 1.2.0 are the highest and lowest versions that may be excluded. There can be an unlimited number of <compatible> tags inside a package.xml.

<dependencies>

<dependencies> -- Dependency Specification in package.xml 2.0

Introduction to dependencies in package.xml 2.0

Dependencies are the most difficult aspect of programming. Using code written by other people can be a nightmare without simple ways to control bugs and API changes. Arguably, the handling of dependencies is PEAR's greatest strength, although there are many other nice features. Regardless of your personal opinion of the importance of dependencies, it is crucial to understand how to specify a dependency, and the different ways to ensure that your package is only used on systems that support it.

In package.xml 1.0, dependencies were relatively simple, but at the cost of usefulness. Specifying a dependency on a package for applications was actually dangerous. If you wished to limit an installed version of a package to a single version, it would mean preventing upgrade at any cost. package.xml 2.0 provides a simple way to enforce stricter dependency versioning without making upgrades onerous.

In package.xml 1.0, dependencies on PHP extensions like PECL extensions was near to a disaster. Extensions had to be present in the php.ini and loaded in memory in order to validate as being installed. This is often impossible, as a different php.ini is used for a production website versus the php.ini used for the pear installer. With package.xml 2.0, dependencies on a PECL-like extension is simple and straightforward, and only requires that the package be installed, and not that the extension be present in memory, although an older style extension dependency is also supported.

package.xml 1.0 supports two kinds of dependencies, required and optional. package.xml 2.0 also supports these two dependency types, but introduces a new kind of dependency concept: an optional dependency group. Dependency groups define a feature set. Instead of thinking "This package optionally depends on Net_FTP and optionally depends on Log" think "To remotely install packages, I need the remoteinstall feature, which needs Net_FTP and the Log package". This grouping allows defining sets of packages and extensions that comprise a feature and must be installed all at once for the feature to function properly.

package.xml 1.0 only supported php, package, and extension dependencies. package.xml 2.0 supports dependencies on php, package, extension, os, architecture, and PEAR installer. In addition, package.xml 2.0 supports depending on a static package located at a url, and depending on a package that provides an extension to PHP like PECL packages.

The PEAR installer dependency is not a dependency on the PEAR package, but a dependency on the currently running PEAR installer, and is more similar to a PHP dependency in that it requires the specified version to be running in memory. This is very useful for circumventing difficult bugs in the PEAR installer that render a package install useless.

Structure of <dependencies>

The <dependencies> tag re-organizes dependencies into groups and "extracts" attributes into tags. It also un-abbreviates words for clarity and human-readability. The following excerpt of a package.xml version 1.0:

<deps>
 <dep type="pkg" rel="ge" version="1.3.1">Archive_Tar</dep>
 <dep type="php" rel="ge" version="4.2.0"/>
 <dep type="pkg" rel="has" optional="yes">PEAR_Frontend_Web</dep>
</deps>

Approximately translates into this format in package.xml 2.0:

<dependencies>
 <required>
  <pearinstaller>
   <min>1.4.0a7</min>
  </pearinstaller>
  <php>
   <min>4.2.0</min>
   <max>6.0.0</max>
  </php>
  <package>
   <name>Archive_Tar</name>
   <channel>pear.php.net</channel>
   <min>1.3.1</min>
  </package>
 </required>
 <optional>
  <package>
   <name>PEAR_Frontend_Web</name>
   <channel>pear.php.net</channel>
  </package>
 </optional>
</dependencies>

These changes were made to simplify xml validation and parsing. Note that unlike package.xml 1.0, the <pearinstaller> and <php> dependencies are required in all package.xml. In addition the <min> tag is required in both <pearinstaller> and <php> dependencies.

<pearinstaller> dependencies

The <pearinstaller> dependency defines the minimum version of PEAR that can properly parse and install the package.xml containing it. As with all dependency tags that support versioning, these 4 tags are supported to define versioning:

  • <min> - minimum version of PEAR required to install this package.xml. This tag is required in all package.xml <pearinstaller> dependencies.

  • <max> - maximum version of PEAR installer supported. Use with caution! This tag will prevent the package from being installed by anyone with a newer version of PEAR!

  • <recommended> - recommended version of PEAR installer. This tag is used for strict version control. The installer will refuse to install a package without the --force option unless the version exactly matches recommended. This can be used to provide a level of extra security, as a package can be set to install using a version that is known to work without limiting future upgrades.

  • <exclude> - incompatible versions of PEAR installer. Use this to prevent the package from being installed by any PEAR version that cannot properly install the package. Multiple <exclude> tags may be used to exclude more than one version.

<php> dependencies

As with all dependency tags that support versioning, these 4 tags are supported to define versioning:

  • <min> - minimum version of PHP required to install this package.xml. This tag is required in all package.xml <php> dependencies.

  • <max> - maximum version of PHP supported.

  • <exclude> - incompatible versions of PHP. Use this to prevent the package from being installed by any PHP version that cannot properly work with the package. Multiple <exclude> tags may be used to exclude more than one version.

<subpackage> dependencies

Subpackage dependencies share the same xml format as package dependencies. The subpackage dependency should only be used if a package is split into more than one package. In other words, if the child package contains the same files as any earlier version of the parent package, the child package would normally conflict with the parent package because it would be attempting to overwrite the parent package's files with its own files.

A simple example should make this clear. Package Foo 1.0.0 contains Foo.php and Foo/Bar.php. Package Foo's developers decide to split Foo into two packages: Foo and Foo_Bar. Foo 1.1.0 contains foo.php, and Foo_Bar 0.1.0 contains Foo/Bar.php. Foo_Bar 0.1.0 conflicts directly with Foo 1.0.0, as both contain the file Foo/Bar.php.

If Foo has a subpackage dependency on Foo_Bar, then the installer will ignore the conflict between Foo 1.0.0's Foo/Bar.php and Foo_Bar 0.1.0's Foo/Bar.php just as it ignores the conflict between Foo 1.0.0's Foo.php and Foo 1.1.0's Foo.php.

<package> dependencies

Understandably, the <package> dependency is PEAR's most complex dependency. PEAR 1.4.0 supports 3 different kinds of package dependencies:

  1. Normal, traditional channel server-based package dependencies (same idea as package.xml 1.0).

  2. Dependencies on packages that provide PHP extensions (like PECL packages). (These can be both server-based and uri-based dependencies)

  3. Static, non-traditional uri-based package dependencies.

channel-based <package> depedendencies

The most common kind of package dependency is a channel-based dependency. This dependency from package.xml version 1.0:

<deps>
 <dep type="pkg" rel="has">PEAR</dep>
</deps>

translates to this dependency in package.xml version 2.0:

<dependencies>
 <required>
<!-- ... -->
  <package>
   <name>PEAR</name>
   <channel>pear.php.net</channel>
  </package>
 </required>
</dependencies>

Note that <channel> is a required tag for all typical package dependencies. Use pear.php.net for all packages that were packaged using package.xml 1.0, regardless of where they are downloaded from.

As with all dependency tags that support versioning, all standard versioning tags are supported (min, max, recommended, exclude). In addition, the <conflicts> tag is supported to create a negative dependency.

  • <min> - minimum version of a dependency. If the dependency package is installed, and is older than this version, installation will fail.

  • <max> - maximum version of a dependency. If the dependency package is installed, and is newer than this version, installation will fail.

  • <recommended> - recommended version of a dependency. This tag is used for strict version control. The installer will refuse to install a package without the --force option unless the version exactly matches recommended. This can be used to provide a level of extra security, as a package can be set to install using a version that is known to work without limiting future upgrades.

    Note that use of the <compatible> tag in the dependency's package.xml can be used to circumvent the installer's strictness. In essence, the <compatible> tag tells the installer that a dependent package is compatible with the current package, even though it is not the recommended version.

  • <exclude> - incompatible versions of a package. Multiple <exclude> tags may be used to exclude more than one version of a dependency.

  • <conflicts> - Negates the dependency. If the package is installed, it cannot satisfy the requirements of the dependency or installation will fail.

Here is a rough chart describing how to convert from package.xml 1.0 "rel" attributes to a package.xml 2.0 equivalent.

uri-based <package> dependencies

Let's look at uri-based package dependencies. Here is a simple example:

<package>
 <name>Foo<name>
 <uri>http://www.example.com/Foo-1.3.0</uri>
</package>

This dependency tells the installer to fetch http://www.example.com/Foo-1.3.0.tgz or http://www.example.com/Foo-1.3.0.tar (both must be available!) if the package Foo is not installed. All uri packages must contain a <uri> tag rather than a <channel> tag and will automatically belong to the pseudo-channel "__uri", but that is not important to the discussion of how to format the xml to create the uri-based package dependency.

uri-based package dependencies cannot contain any versioning information, as this is irrelevant: there is only one version possible with a static uri. uri-based dependencies can contain the <conflicts/> tag to specify an absolute conflict with the package, and the <providesextension> tag to specify an extension provided by the static package.

PEAR-style <package> dependencies vs. PECL-style <package> dependencies

package.xml 2.0 supports differentiating release types, and as such also supports dependencies on PECL-style packages that use the extbinrelease or extsrcrelease type.

To specify a dependency on a PHP extension that can be distributed as a PECL package, but could also be bundled with PHP by default, such as the PDO extension, use this dependency style:

<package>
 <name>PDO</name>
 <channel>pecl.php.net</channel>
 <min>0.3.1</min>
 <providesextension>PDO</providesextension>
</package>

The magic is in the <providesextension> tag. This tag tells the installer to take this process when validating the dependency:

  1. Is the extension "PDO" present in memory? If so, is it version 0.3.1 or higher?

  2. If not, is the user also installing pecl.php.net/PDO at the same time as this package? If so, is it version 0.3.1 or higher?

  3. If not, is pecl.php.net/PDO installed, and is the version 0.3.1 or higher?

If any of the three conditions above validate in the order specified, the dependency will be satisfied and installation will continue. This system allows users to use a different php.ini to install PHP extensions and also provides a fail-safe system to depend on extensions.

Внимание

<providesextension>, like all other extension-related functions in PHP, is case-sensitive. Do not use "pdo" for the "PDO" extension, or your dependency will always fail.

<extension> dependencies

As with all dependency tags that support versioning, all standard versioning tags are supported (min, max, recommended, exclude). In addition, the <conflicts> tag is supported to create a negative dependency.

  • <min> - minimum version of PHP extension to install this package.xml.

  • <max> - maximum version of PHP extension supported.

  • <recommended> - recommended version of PHP extension. This tag is used for strict version control. The installer will refuse to install a package without the --force option unless the version exactly matches recommended. This can be used to provide a level of extra security, as a package can be set to install using a version that is known to work without limiting future upgrades.

  • <exclude> - incompatible versions of PHP extension. Multiple <exclude> tags may be used to exclude more than one version.

  • <conflicts> - Negates the dependency. If the extension is present, it cannot satisfy the requirements of the dependency or installation will fail.

<os> dependencies

The OS dependency is used to restrict a package to both a particular class of OSes (like unix) and to a specific OS (like darwin, or freebsd). Here is an example:

<os>
 <name>linux</name>
</os>

To specify that a package can be installed on every OS except the one specified, use the <conflicts/> tag:

<os>
 <name>windows</name>
 <conflicts/>
</os>

Possible OS values are:

  • windows

  • unix

  • linux

  • freebsd

  • darwin (use for Mac OS X)

  • sunos

  • irix

  • hpux

  • aix

In addition, any esoteric OS that supports the php_uname() function can be used. Note that the "unix" OS is defined as any of linux, freebsd, darwin, sunos, irix, hpux, or aix.

<arch> dependencies

The arch dependency is used to restrict a package to a specific os and processor architecture. Here is an example:

<arch>
 <pattern>linux-*-i386-*</pattern>
</arch>

To specify that a package can be installed on every architecture except the one specified, use the <conflicts/> tag:

<arch>
 <pattern>linux-*-i?86-*</pattern>
 <conflicts/>
</arch>

The arch pattern is defined by the OS_Guess->matchSignature() method, and is as follows: sysname[-release[-cpu[-extra]]]. All segments within [] are optional, and the wildcard "*" can be used in all segments instead of a value. In addition, the "?" wildcard can be used to specify a single character that can match any value. i?86 will match i386, i686, i586 and so on.

sysname is the same as the os dependency, except unix is not supported.

release is the version of the operating system.

cpu is the specific cpu, and is typically i?86, sparc, powerpc.

extra is any other stuff on the end of php_uname(), including the glibc version

<usesrole>

<usesrole> -- documenting custom file roles used in <contents>

Documenting custom file roles

Standard file roles provided by default with PEAR are:

  • php

  • data

  • doc

  • test

  • script

  • src

  • ext

If your package chooses to use a role provided by a third party that implements some more advanced file installation handling, all you need to do is specify the role in the xml for the <file> tag that contains it like so:

<file role="foo"/>

However, if a user does not have the package installed that provides the custom role "foo", then the error message on installation will simply say "unknown role 'foo'", which is not very helpful.

The <usesrole> tag instead prompts the installer to tell the user "this package uses the custom role 'foo', install package pear.example.com/Foo to use"

<usesrole>
 <role>foo</role>
 <package>Foo</package>
 <channel>pear.example.com</channel>
</usesrole>

Note that static URI packages (channel-less packages) are also supported:

<usesrole>
 <role>foo</role>
 <uri>http://pear.example.com/Foo-1.2.0</uri>
</usesrole>

<usestask>

<usestask> -- documenting custom tasks used in <contents>

Documenting custom file tasks

Standard file tasks provided by default with PEAR are documented in this location.

If your package chooses to use a task provided by a third party, all you need to do is specify the task as part of the xml for the <file> tag that contains it like so:

<file role="php">
 <tasks:foo/>
</file>

However, if a user does not have the package installed that provides the custom task "foo", then the error message on installation will simply say "unknown task 'foo'", which is not very helpful.

The <usestask> tag instead prompts the installer to tell the user "this package uses the custom task 'foo', install package pear.example.com/Foo to use"

<usestask>
 <task>foo</task>
 <package>Foo</package>
 <channel>pear.example.com</channel>
</usestask>

Note that static URI packages (channel-less packages) are also supported:

<usestask>
 <task>foo</task>
 <uri>http://pear.example.com/Foo-1.2.0</uri>
</usesrole>

<phprelease>, <extbinrelease>, <extsrcrelease>, <bundle>

<phprelease>, <extbinrelease>, <extsrcrelease>, <bundle> -- specifying the content type of a release

Documenting release type

In package.xml 1.0, there was one release type. package.xml 2.0 provides much finer control over the kind of release in order to provide three new release types: extension binary release, extension source release, and package bundle release.

All of the normal release tags (phprelease, extsrcrelease, extbinrelease) may contain two optional sections, <installconditions> and <filelist>. The purpose of these sections is to allow specification of different file install groups based on the target OS for installation, or other common install conditions.

To be clear: in package.xml, there was 1 <release> tag. package.xml 2.0 allows several adjacent release tags, each specifying a different install set. This actually simplifies complex installation filesets by separating the contents listing of the tarball from how the installer should manipulate this listing. Debugging installation file sets should be much simpler with this change.

The <filelist> tag can contain only two possible tags, <install> and <ignore>. install has two required attributes, "name" and "as". The install tag is used in the same manner as package.xml's install-as attribute for the <file>, to specify a new installation location for a file in the contents list. The ignore tag is used to completely ignore a file.

The <installconditions> tag can contain 4 tags whose format can be found in the <dependencies> section: <php>, <extension>, <os>, and <arch>. Each tag can appear exactly once except for the extension tag, which can appear limitless times.

The php tag is used to specify a php version or range of versions that an install set should be valid with.

The extension tag is used to specify extensions that must be present for an install set to be valid.

The os tag is used to specify an OS that must be present for an install set to be valid. Note that unix can be used to match all flavors, and linux can be used to match all linux-based OSes. Darwin should be used for Mac OS X, and * can be used to match all operating systems.

The arch tag is used to specify a uname string or portion of a uname string that must match in order for the install set to be valid.

<phprelease>

The phprelease release type is designed for PEAR-style PHP script package releases. It causes a few specific validation changes. First of all, the <contents> tag must contain <file> and <dir> tags. The only valid roles for files are role="php", role="data", role="doc", and role="test" plus any custom roles that the user has installed for use in php releases.

<extsrcrelease>

The extsrcrelease release type is for PECL-style PHP extension releases that must be compiled in order to be useable. It causes a few specific validation changes. First of all, the <contents> tag must contain <file> and <dir> tags. The only valid roles for files are role="src", role="data", role="doc", and role="test" plus any custom roles that the user has installed for use in extension source releases.

In addition, the <providesextension> tag must be present in order to document the name of the extension this package provides must be in the package.xml as well.

<extbinrelease>

The extbinrelease release type is for PECL-style PHP Extension binary releases that are pre-compiled. It causes a few specific validation changes. First of all, the <contents> tag must contain <file> and <dir> tags. The only valid roles for files are role="ext", role="data", role="doc", and role="test" plus any custom roles that the user has installed for use in extension binary releases.

In addition, the <srcpackage> or <srcuri> and the <providesextension> tags must be present in order to document the package that provides extension source for this binary release, and the name of the extension this package provides must be in the package.xml as well.

<bundle>

The bundle release type is designed to allow packaging several other package releases into a single bundle of packages that will all be installed at the same time. This can be used to distribute a complete application as one tarball, or to distribute a library of packages in a single tarball.

Unlike the other release types, a bundle release's <contents> tag must contain only the <bundledpackage> tag. The contents of the bundledpackage should be release names like "Foo-1.2.3.tgz"

In addition, the <bundle/> tag must be empty.


Глава 18. Публикация пакета

Шаги, которые необходимо выполнить мэйнтейнеру для публикации пакета.

Вводная

Первый шаг, который вы должны выполнить - это проверить, что при написании пакеты вы учли Стандарты кодирования PEAR. После этого вам следует получить разрешение на публикацию пакета от сообщества PEAR (на данный момент это означает, что вам нужно 5 голосов "за" (+1)).

После того, как вы получили достаточное количество голосов "за" и ваш пакет соответствует стандартам, вам следует обратиться за получением учетной записи на сайте PEAR. Для этого вы можете использовать форму запроса учетной записи - http://pear.php.net/account-request.php. После получения учетной записи вы можете переходить к следующему шагу.


Создание tar-архива релиза

Теперь, когда у вас уже есть файл описания пакета, вы можете создать tar-архив релиза. В командной строке смените текущую директорию на директорию пакета и выполните команду: pear package <package definition XML file> В результате создастся tar-архив релиза пакета (сжатый с помощью gzip, если будет найдена zlib). Этот файл в дальнейшем будет ипользован для публикации пакета.

Далее вам следует установить пакет локально, выполнив команду: pear install <file> (file - это tar-архив, который вы только что создали). Это необходимо для того, чтобы удостовериться в том, что файл описания пакета содержит не только правильный XML, но и правильные данные. Вы должны вручную проверить, что каждый файл установился в соответствующее место. Если ваш пакет содержит тестовые скрипты (что настойчиво рекомендуется) - выполните их.

Если на этом этапе происходят какие-либо ошибки, вам следует их исправить и проделать всю процедуру создания пакета сначала. Когда все будет в порядке - переходите к следующему шагу.


Публикация пакета с помощью веб-интерфейса

Для начала, вы должны зайти на сайт PEAR, используя пароль и логин, которые были вам выданы (см. первый шаг).

Если это первый релиз вашего пакета, то вы должны зарегистрировать его. Регистрация осуществляется с помощью формы, которая расположена здесь: http://pear.php.net/package-new.php. Если вы сомневаетесь к какой категории должен относиться ваш пакет - проконсультируйтесь у сообщества PEAR (с помощью рассылки pear-dev).

Теперь, наконец, вы можете опубликовать пакет. Делается это с помощью соответствующего веб-интерфейса. Используйте форму: http://pear.php.net/release-upload.php.

Всё! Ваш пакет был выпущен; анонс был разослан в списки рассылки; все довольны, все смеются =)


Глава 19. Supporting PEAR development

How to support the PEAR community

There are numerous ways to support the PEAR project, that are described in this part of the guide.


Глава 20. Recommendations

Why recommendations?

The following recommendations describe topics which were discussed and agreed upon by the PEAR developers on the developers mailinglist. They aren't strict rules, which you need to follow (like Coding Stardards), but are intended as guidelines for a common API scheme and easier package interoperability. Please consider following them in your packages where possible.


Color Representation inside PEAR Packages

In case a package has to deal with colors, it is recommended that developers store and use an array representation of the color values in their PEAR packages. All values are in the range of 0..255.


Conversion to/between the color-representations

The PEAR-package Image_Color will (hopefully soon) contain all needed functions to convert arbitrary color formats to the internal RGBA representation and convert different color representations.

Status: Currently Image_Color already offers functions to convert color-names (e.g. "green") and hex-representations-strings (e.g. "#339900") to the PEAR-RGBA-format. We are working to get alpha- channel support added hopefully soon and will later add funtions for CYMK-conversion as well.


Глава 21. Writing documentation

This chapter provides a detailed description how to write documentation using one of the supported formats. It is aimed at both PEAR developers that are already maintaining packages in PEAR and at people who are planning to contribute a new package.


The DocBook XML format

DocBook is an XML dialect that is used by a wide range of projects to maintain their documentation. Examples for DocBook usage in OpenSource projects are the documentations of KDE and PHP. PEAR has opted for using DocBook, because we believe that it provides a solid foundation for the technical documentation for PEAR packages.

The trade-off for using DocBook is that it is relatively hard to use. Testing documentation requires a number of tools to be installed and one needs to learn a (not very complicated) XML dialect. Once one is familiar with how DocBook works, they will enjoy writing documentation with it though.

The book [DocBook: The Definitive Guide], written by Norman Walsh and Leonard Muellner and published by O'Reilly & Associates, Inc., is available online and it makes up a great resource for people interested in learning DocBook.

Definitely check out the book's "DocBook Element Reference" section. This portion provides detailed information about each element, including which elements can (and must) be used as parents and children.


Required software

Even if DocBook XML can (like any other XML file) be written using a normal text editor, it is optimal for users to install some software on their machine in order to test the validity of the documenting efforts. A list of the required software and a installation instruction can be found in the PHP Documentation HOWTO. Apart from providing information about the software, this HOWTO also provides a ton of other useful information that goes far beyond this chapter. One is encouraged to completely read it. (Chapter II can be skipped, because it only contains information that is very PHP specific.)

Installation on OS X: The PHP Documentation HOWTO advises users of Mac OS X to use packages provided by Fink. Alternatively packages from the MacPorts project can be used. After installing MacPorts, the toolchain can be installed using the following command:

Unfortunately, installing that software can be difficult under some circumstances. If you are unable to get it working, don't use that as an excuse for not writing documentation. There are two test servers that automatically download peardoc from CVS and build the manual. Any parsing errors your changes cause will show up in the logs the next time the build happens:

Build from Mika Tuupola (log) (time zone: EET = UTC+2, EEST = UTC+3, updated every two hours)
Build from TAKAGI Masahiro (log) (updated daily at 06:00 JST = 21:00 UTC)

These automatic builds also give you an idea of what your changes will look like in the actual manual. This is helpful because the manual on the PEAR website is only built once per week (Sundays ~12:00 UTC).

Внимание

The manual on the PEAR website is built only once per week. Any XML validation errors will cause the build to fail. If the main build fails, the old version remains in place, meaning the manual will be out of date. Therefore, always check the test build logs to ensure your changes are valid. More importantly, do not commit updates shortly before the main build happens (Sundays ~12:00 UTC).

Once the necessary software is in place, one has to get the latest version of the XML sources from PEAR's CVS repository:


$ cvs -d :pserver:<user>@cvs.php.net:/repository login
     
     
[password]
     
     
$ cvs -d :pserver:<user>@cvs.php.net:/repository co peardoc
     

If you do not own an account for cvs.php.net, please choose cvsread as the username. When asked for the password, type phpfi.

After that the directory ./peardoc will contain a local copy ("sandbox") of the latest sources. If you are not yet familiar with CVS, then the online book "Open Source Development with CVS" will provide you with all the necessary information.


Writing documentation

Instead of a long and boring description for writing documentation using DocBook, we would like to point you to a bunch of "reference documents", from which you should be able to learn quickly:

  • peardoc/en/authoring

    The CVS tree has a complete set of DocBook XML templates. These files provide the standard of how PEAR documentation should look.

    The simplest way to utilize them is to copy them to your working directory, rename them accordingly, edit the contents to match the reality of your program and then upload them to your package's directory in the repository.

  • HTTP Request

    The documentation for HTTP_Request, which is a relatively small package, only consists of a bunch of end-user documentation, which describes all of the basic features of the package. Each feature description includes at least one example. For small packages with only a handful of methods this documentation type is absolutely enough.

  • XML Beautifier

    XML_Beautifier is a package that is also relatively compact, but which supports different configuration options. These options are described in the documentation Additionally the documentation gives usage examples and (unlike HTTP_Request) also includes API documentation for its methods.

  • DB

    DB is a large PEAR package and has excellent documentation, including usage examples. The DB docs carefully adhere to the formatting specified in peardoc/authoring. The link above goes to the DocBook source code in the CVS repository. It might be helpful to examine the HTML generated therefrom.

In addition to the examples above, you will find much more documentation examples by browsing the peardoc directory, which contains your local version of the CVS tree. Especially the directory peardoc/en/packages/ should be of interest for you. You can also browse the CVS module using the web interface, including the raw XML for the file you are presently reading.


Testing documentation


Using xmllint

Alternatively one can use the xmllint program that is part of the libxml2 toolkit. This is especially useful for systems where the DSSSL/make setup does not work properly.

In addition to testing the well-formedness of the DocBook sources, xmllint can also check the semantical correctness with the help of RELAX NG schemas. The schema files for DocBook are available as a ZIP package from docbook.org. After unzipping the package into the directory relaxng/ inside the peardoc source folder, one can run xmllint from the root folder of the PEAR documentation as follows:

xmllint --valid --noout --relaxng relaxng/ manual.xml


Partial builds

The build process (not the test builds, which are reasonably quick) actually takes a very long time which makes debugging and testing a very hard task. In order to increase build performance, the script make-partial.php in the root directory of the documentation module may be used. This is an interactive command line script that will enable to you to selectively include the different parts of the manual. In the following example a version of the manual is generated which only contains a certain part of the Developer's Guide and the documentation for the HTTP packages. Using these partial builds reduces the build time dramatically.


peardoc$ ./make-partial.php
Include about-pear? [NO] 
Include guide-newmaint? [NO] 
Include guide-developers? [NO] y
Include guide.developers.intro? [NO] 
Include guide.developers.meaning? [NO] 
Include guide.developers.contributing? [NO] 
Include guide.developers.packagedef? [NO] 
Include guide.developers.release? [NO] 
Include guide.developers.supporting? [NO] 
Include guide.developers.recommendations? [NO] 
Include guide.developers.documentation? [NO] y
Include core? [NO] 
Include packages? [NO] y
Include package.authentication? [NO] 
Include package.benchmarking? [NO] 
Include package.caching? [NO] 
Include package.configuration? [NO] 
Include package.console? [NO] 
Include package.database? [NO] 
Include package.datetime? [NO] 
Include package.encryption? [NO] 
Include package.fileformats? [NO] 
Include package.filesystem? [NO] 
Include package.gtk? [NO] 
Include package.html? [NO] 
Include package.http? [NO] y
Include package.images? [NO] 
Include package.internationalization? [NO] 
Include package.logging? [NO] 
Include package.mail? [NO] 
Include package.math? [NO] 
Include package.networking? [NO] 
Include package.numbers? [NO] 
Include package.payment? [NO] 
Include package.pear? [NO] 
Include package.php? [NO] 
Include package.science? [NO] 
Include package.streams? [NO] 
Include package.structures? [NO] 
Include package.system? [NO] 
Include package.text? [NO] 
Include package.tools? [NO] 
Include package.xml? [NO] 
Include package.webservices? [NO] 
Include pecl? [NO] 
CONFIG_FILES=manual.xml CONFIG_HEADERS= ./config.status
creating manual.xml
/usr/bin/jade -wno-idref  -d html.dsl -V use-output-dir -t sgml ./phpdocxml.dcl manual.xml
         

Tips for good documentation

This section of the chapter does not deal with the specifics of organizing documentation in the peardoc standard, but instead with how to organize documentation logically.

  1. First, every package solves a problem. What is this problem? Try to figure out what assumptions your end-users might not have about the problem (they may not realize that this is a problem that needs solving). For instance, a template package solves the problem of both separating design from code, and separating business logic from display logic. If possible, explain the problem in terms that even a novice programmer can understand.

  2. Next, how does the package uniquely solve the problem? This is something that most documentation lacks. For example, there are many template engines. All of them solve the same problem, but none of them do it in the same way. A block-based template engine does not have any logic at all, whereas a template like Smarty defines a whole new template language. Some template engines compile their templates, others don't. What is unique about your package? Can someone who has never seen the code get a good idea of how it solves the problem?

  3. Provide examples! Start right away with simple examples that shows the basic feature set -- they will show users how to quickly start using the package. More complex examples will help the users in understanding advanced ways of using the package.

  4. If your package exposes complex interfaces or multiple constants that can't be fully explained in one or two examples (which is very likely), do not miss to explain them thoroughly in the documentation. Document any interfaces that users must use, such as a database DSN, command-line arguments for applications, configuration file contents, or any other non-code element.

  5. Last, proofread your documentation. If possible, have someone else who is not as familiar with your project take a look at the documentation. They will catch assumptions that you have missed.

IV. New features in PEAR 1.4


Глава 22. Introduction

The debut of PEAR 1.4.0 is very exciting. This chapter documents all of the differences between PEAR 1.3.x and the new features introduced in PEAR 1.4.

The most significant change in PEAR 1.4 is the addition of channels, a simple and effective method of distributing application development. This change has driven most of the other changes to PEAR, and in fact full application support is a major goal of this release.

In addition to channels, support for customization of the install process has been seriously enhanced with the addition of three essential features for application development:


Глава 23. Channels

PEAR Channels provide a robust and effective way of distributing development. The addition of channel support to the PEAR installer as of version 1.4.0 means that it is now simpler to distribute any PHP code project using the PEAR installer than it ever was. PEAR Channels allow developers of applications to effectively depend upon packages from pear.php.net and any other source that provides a channel server. For users of these applications, this eliminates the complexity of installation and configuration. Now, all the user will need to do is to type a single pear install channel/Packagename command and go!

Before PEAR 1.4.0, the only solution to depending on code from several sources is to bundle the code. This has several bad side effects, the most obvious of which is that code size increases dramatically, and makes upgrading for a minor bug fix a complicated download for the user.

Channels allow an application developer to depend on packages from pear.php.net, a package from pear.example.com, and others. The user will only need to install/upgrade from a single source using the pear installer. With the current state of affairs, the pear installer is only really useful for installing, well, PEAR packages. Because of this difficulty (among others), traditionally very few packages are available as PEAR packages that can be installed with the PEAR installer.

PEAR 1.4.0+ aims to eliminate this and other barriers to application development.

Incomplete documentation

Documentation is not yet complete

channel.xml

channel.xml -- The channel definition file

How to describe a channel

Discovery of a channel's capabilities is extremely flexible. The XSD schema defining channel.xml can be found at http://pear.php.net/dtd/channel-1.0.xsd. Channel.xml defines:

  1. the channel name

  2. an optional suggested user alias for the channel

  3. a brief summary of the channel's purpose

  4. an optional package to perform custom validation of packages on both download and packaging

  5. a list of protocols supported by a channel (XML-RPC, SOAP, and REST are supported)

  6. a list of mirrors and the protocols they support.

Here is a sample channel.xml with all elements:

<channel version="1.0"
         xsi:schemaLocation="http://pear.php.net/channel-1.0
                             http://pear.php.net/dtd/channel-1.0.xsd">
 <name>pear.example.com</name>
 <suggestedalias>foo</suggestedalias>
 <summary>Example channel.xml</summary>
 <validatepackage version="1.3.4">Foo_Validate</validatepackage>
 <servers>
  <primary port="8080" ssl="yes">
   <xmlrpc> <!-- default path is xmlrpc.php -->
    <function version="1.0">logintest</function>
    <function version="1.0">package.listLatestReleases</function>
    <function version="1.0">package.listAll</function>
    <function version="1.0">package.info</function>
    <function version="1.0">package.getDownloadURL</function>
    <function version="1.1">package.getDownloadURL</function>
    <function version="1.0">package.getDepDownloadURL</function>
    <function version="1.1">package.getDepDownloadURL</function>
    <function version="1.0">package.search</function>
    <function version="1.0">channel.listAll</function>
   </xmlrpc>
   <rest> <!-- no default path, all must be defined in baseurl -->
    <baseurl type="package">http://pear.example.com/rest/1.0/package</baseurl>
    <baseurl type="category">http://pear.example.com/rest/1.0/category</baseurl>
   </rest> 
   <soap path="soapy.php"> <!-- default path is soap.php -->
    <function version="1.0">package.listAll</function>
   </soap>
  </primary>
  <mirror server="foo2.example.com/pearmirror">
   <xmlrpc path="mirrorxmlrpc.php"> <!-- default path is xmlrpc.php -->
    <function version="1.0">package.listLatestReleases</function>
    <function version="1.0">package.listAll</function>
    <function version="1.0">package.info</function>
    <function version="1.0">package.getDownloadURL</function>
    <function version="1.1">package.getDownloadURL</function>
    <function version="1.0">package.getDepDownloadURL</function>
    <function version="1.1">package.getDepDownloadURL</function>
    <function version="1.0">package.search</function>
   </xmlrpc>
   <rest> <!-- no default path, all must be defined in baseurl -->
    <baseurl type="package">http://foo2.example.com/rest/1.0/package</baseurl>
   </rest> 
  </mirror>
 </servers>
</channel>

<name>

A channel's name should be the name of the server that users would browse to in order to learn more about the packages being offered. For instance, PEAR packages are located in the pear.php.net channel. PECL packages are located in the pecl.php.net channel. Note that for backwards compatibility, all existing packages based on package.xml version 1.0 are in the pear.php.net channel.

The benefit that comes from using the server name as the channel name is that auto-discovery becomes a real possibility, as well as ease of locating packages increases dramatically.

A channel need not be located in the document root, a channel can contain a path. This is a perfectly valid channel name: foo.example.com/path/to/pear. Note that users would have to type:

$ pear install foo.example.com/path/to/pear/Packagename

Unless you provide a <suggestedalias>.

The channel's definition file "channel.xml" must be placed in the root channel directory. If a channel is "pear.example.com", the channel.xml must be located in "http://pear.example.com/channel.xml". If the channel is "pear.example.com/path/to/pear", then the channel.xml must be located in "http://pear.example.com/path/to/pear/channel.xml"

<suggestedalias>

<suggestedalias> defines a shorter, more friendly name to use when installing packages from a channel. For instance, the pear.php.net channel's suggested alias is "pear". The best aliases for a channel will be no more than 6 characters long - remember, a user must type them often when installing or upgrading, and this can be tedious for longer aliases.

Rather than call this tag <alias>, as it was originally named, the tag is named <suggestedalias> in order to provide the user some latitude. If the user does not like the alias suggested by the channel owners, he or she can easily re-alias a channel through the channel-alias command.

<summary>

This tag provides a short description of what packages the user should expect to find on this channel. The summary is what users will see when the use the list-channels command.

<validatepackage>

Most channels will be satisfied with the restrictions placed upon package naming, versioning, and so on that PEAR provides by default. However, for some channels, the validation will be too strict, and others, too relaxed. The <validatepackage> tag provides the next level of customization.

If omitted, the installer assumed that the PEAR_Validate class should be used. Note that a looser version validation is provided by the PEAR_Validate_PECL class, for channels like pecl.php.net that do not wish to deal with PEAR's warnings on version transgressions.

<validatepackage> requires a version attribute and text content. The text content must be the name of a package that can be installed via:

$ pear install channelname.example.com/Packagename-version

as in:

$ pear install pear.example.com/Foo_Validate-1.3.4

for the sample channel.xml at the beginning of this section. In addition, the package must provide a single class named after the package in a file using the PEAR naming conventions (all underscores "_" converted into path separators "/" so that Foo_Validate is located in Foo/Validate.php), and this class should extend PEAR_Validate. Methods beginning with "validate" like validateVersion() are intended to be overridden by validation classes for use in extending existing validation functionality.

<servers>: <primary> and <mirror>

Mirroring is explicitly supported in channel.xml and in the PEAR installer. Users can choose their favorite mirror via the default_channel configuration option, and channel.xml can list all the possible mirrors using the (surprise) <mirror> tag.

The <primary> tag is used to define the location of protocols, and to list the protocols that are supported by the main channel server. Optional attributes can be used to modify how the PEAR installer will attempt to connect to the server. The "port" attribute can be used to define how the installer will connect to XML-RPC and SOAP services. REST services are always controlled by the individual <baseurl> tags.

<xmlrpc>, <soap>, <rest>

channel.xml knows about the XML-RPC, SOAP, and REST protocols for web services. However, the PEAR installer only supports XML-RPC currently, and may support REST shortly. No support for SOAP is planned for the near future. However, should it ever be implemented, channel.xml is ready.

The <xmlrpc> and <soap> tags have identical formats. Both tags can contain an optional attribute "path" that tells the PEAR installer which URL to query. By default, the path is protocol.php, as in xmlrpc.php or soap.php. In other words, to access XML-RPC functions for the pear.example.com channel defined in the sample channel.xml, the installer would query https://pear.example.com:8080/xmlrpc.php for XML-RPC functions, but would query https://pear.example.com:8080/soapy.php for SOAP functions.

The <rest> tag reflects the design concept behind REST: each resource is defined by a base URL in tag <baseurl> that is then used by the installer along with hyperlinks to glean the same information that XML-RPC or SOAP would provide. Required attribute "type" tells the installer what kind of information is provided by the base URL, and how to parse that information.

<function>

The <function> tag is quite simple. A required version attribute informs the installer what the API is, and the text content informs the installer what the name of the function is. Note that multiple functions with different versions can co-exist peacefully, as in:
<function version="1.0">package.getDownloadURL</function>
<function version="1.1">package.getDownloadURL</function>
If a newer API is backwards-compatible, always define every possible API version in order to prevent older installer versions from giving up.

Why not use a standard such as wsdl?

Some of you may be asking "why create another standard for web services discovery?" The answer is simple: channel.xml does not supplant the role that WSDL has for java, or XML-RPC introspection occupies. channnel.xml is a layer on top of these technologies. The point is to quickly list the remote protocols that are supported, not to describe what they do.

The PEAR installer is specialized enough that a generic listing of parameters and return values is entirely unnecessary: the installer knows exactly what xml-rpc function package.info version 1.0 requires and what it returns. Any other information simply adds wasted bandwidth and disk space.

XML-RPC functions

XML-RPC functions -- XML-RPC function API documentation

What XML-RPC functions are available in a standard channel?

A standard PEAR channel should support this list of XML-RPC functions:

Channels can also implement channel.listAll, but we recommend that this only be implemented by pear.php.net and pecl.php.net channels, as the command is utilized by the update-channels command to retrieve an official list of channels.

logintest

The logintest xml-rpc function is called by the login command, and should return a boolean TRUE

package.getDownloadURL

false|struct packageinfo

an array of format:

array(
        'channel' => channel name,
        'package' => package name,
        ['version' => specific version to retrieve,]
        ['state' => specific state to retrieve,]
     )

if both version and state are set, the version index should be ignored.

string preferred_state = stable

The client-side preferred_state. This should be used to exclude releases that are too unstable.

string installed_version = false

The current installed version of the package on the client-side. This will either be a version string, or false if the package is not installed. Use this to ensure that older versions are never returned (as defined by version_compare(possible_version, installed_version, "<")).

The package.getDownloadURL function should return an array with either two or three indices.

  • "version" => version of the release returned

  • "info" => the complete package.xml contents from the release

  • "url" => a URL from which to download this release. If no releases exist that fit the constraints defined by preferred_state, installed_version, and the version/state indices of packageinfo, then do not return this index, and instead return the version and package.xml of the latest release.

    The url entry should NOT append .tgz or .tar, but should be something like "http://pear.php.net/get/PEAR-1.4.0" instead of "http://pear.php.net/get/PEAR-1.4.0.tgz"

Note that version 1.0 of package.getDownloadURL did not have the installed_version parameter. Version 1.1 of package.getDownloadURL does - that is the only difference between the two versions.

package.getDepDownloadURL

string xsdversion

This should be either '1.0' or '2.0', and should match the version attribute from the top-level <package version="X.0"> tag. This should be used to determine how to process the second parameter.

struct dependency

if the first parameter xsdversion is '1.0', this should be an array of format:

array(
        'name' => package name
        'type' => 'pkg' - anything else is an error
        'rel' => 'has', 'ge', 'le', 'lt', 'le', 'not', 'ne'
        ['version' => specific version to retrieve,]
     )

if xsdversion is '2.0', this should be an array of format:

array(
        'name' => package name
        'channel' => package channel - see notes below
        ['min' => minimum version (inclusive),]
        ['max' => maximum version (inclusive),]
        ['exclude' => single version to exclude (string),
                      or array of versions to exclude,]
     )

Note that you must always verify that the channel matches your channel. If your channel server is not at pear.php.net or pecl.php.net, you must reject all xsdversion='1.0' requests, and all xsdversion='2.0' requests where the channel is not your channel.

struct parentpackage

This is information on the parent package, and is an array of format:

array(
        'channel' => channel name,
        'package' => package name,
        'version' => specific version to retrieve,
     )

string preferred_state = stable

The client-side preferred_state. This should be used to exclude releases that are too unstable.

string installed_version = false

The current installed version of the dependency on the client-side. This will either be a version string, or false if the package is not installed. Use this to ensure that older versions are never returned (as defined by version_compare(possible_version, installed_version, "<")).

Like package.getDownloadURL, package.getDepDownloadURL should return an array with either two or three indices.

  • "version" => version of the release returned

  • "info" => the complete package.xml contents from the release

  • "url" => a URL from which to download this release. If no releases exist that fit the constraints defined by preferred_state, installed_version, and the version/state indices of packageinfo, then do not return this index, and instead return the version and package.xml of the latest release.

    The url entry should NOT append .tgz or .tar, but should be something like "http://pear.php.net/get/PEAR-1.4.0" instead of "http://pear.php.net/get/PEAR-1.4.0.tgz"

Note that version 1.0 of package.getDepDownloadURL did not have the installed_version parameter. Version 1.1 of package.getDepDownloadURL does - that is the only difference between the two versions.

package.info

string package

Package name to retrieve information about

string field = null

specific field to retrieve information about. If null, this should return an array with this indices, although others could be set as well:

<?php
array(
    'name' => 'package name',
    'category' => 'category name',
    'license' => 'package license',
    'summary' => 'package summary',
    'description' => 'package description',
    'releases' =>
    array( // all releases indexed by version
        '0.1' =>
        array(
          'license' => 'release license',
          'summary' => 'release summary',
          'description' => 'release description',
          'releasedate' => 'date of release',
          'releasenotes' => 'release notes',
          'state' => 'release stability',
          // the next index is optional
          'deps' =>
          array(
            array( // release dependencies of latest release
              'type' => 'dep type from package.xml <dep>',
              'relation' => 'rel from package.xml <dep>',
              'version' => 'version from package.xml <dep>, or empty string',
              'name' => 'name from package.xml <dep>',
              'optional' => 'yes or no',
            ),
            // and so on with all deps
          ),
        ),
        // and so on with all releases
        // releases should be ordered by releasedate DESC
    ),
);
?>

The second parameter, if set, must be one of these choices:

  • authors - a current list of package maintainers in format:

    <?php
    array(
        'handle1' =>
        array(
          'name' => 'Maintainer Name',
          'email' => 'maintainer@example.com',
          'role' => 'role from package.xml (lead, developer, contributor, helper)',
        ),
        'handle2' =>
        array(
          'name' => 'Maintainer Name 2',
          'email' => 'maintainer2@example.com',
          'role' => 'role from package.xml (lead, developer, contributor, helper)',
        ),
        // etc.
    );
    ?>

  • category - the category this package is in

  • description - the description of the latest release

  • license - package license of latest release

  • notes - release notes of the latest release

  • releases - an array of the format documented above, containing information on all releases

  • summary - summary from latest release


Глава 24. Custom File Roles

Внимание

As of PEAR version 1.4.3, the required format for custom file roles has been changed due to a minor security vulnerability. All custom file roles must now define a Role.xml file in order to properly declare a custom file role. See the example below for more information.

One of the programming features that the PEAR installer enforces is the separation of files into separate categories, and the important idea that files of a similar category are always installed into the same location, or at least handled the same way, as in the case of role="src" for PECL packages.

This has been quite successful for smaller library-style packages, but complete applications cannot function without customized installation locations. For instance, some files may be intended for use in a public web frontend, others for library location. PEAR 1.4 introduces the possibility of defining custom installation roles to fill this void.


Using a customized role in a package.xml

To use a custom installation role that another programmer has written, there are three steps that are necessary. First, the <usesrole> tag should be used to define each custom role that is used in the package.xml. Next, the role should simply be used for the files it pertains to. Finally, a dependency on the package that provides the custom role should be added to the package.xml, just for completeness.

Pretty simple!


Defining a customized role for use in a package.xml

To define a custom role, you need to create a package containing a single file. Here is a sample package.xml that could be a custom role:

<?xml version="1.0"?>
<package version="2.0" xmlns="http://pear.php.net/dtd/package-2.0"
    xmlns:tasks="http://pear.php.net/dtd/tasks-1.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://pear.php.net/dtd/tasks-1.0
http://pear.php.net/dtd/tasks-1.0.xsd
http://pear.php.net/dtd/package-2.0
http://pear.php.net/dtd/package-2.0.xsd">
 <name>Chiarafoo</name>
 <channel>pear.chiaraquartet.net</channel>
 <summary>Chiarafoo role</summary>
 <description>
  The chiarafoo role installs files into your customized Foo directory
 </description>
 <lead>
  <name>Greg Beaver</name>
  <user>cellog</user>
  <email>cellog@php.net</email>
  <active>yes</active>
 </lead>
 <date>2005-03-21</date>
 <version>
  <release>1.0.0</release>
  <api>1.0.0</api>
 </version>
 <stability>
  <release>stable</release>
  <api>stable</api>
 </stability>
 <license uri="http://www.php.net/license">PHP License</license>
 <notes>
  Provides the chiarafoo file role
 </notes>
 <contents>
  <dir name="/" baseinstalldir="PEAR/Installer/Role">
   <file name="Chiarafoo.xml" role="php"/>
   <file name="Chiarafoo.php" role="php">
    <tasks:replace from="@package_version@" to="version" type="package-info"/>
   </file>
  </dir> <!-- / -->
 </contents>
 <dependencies>
  <required>
   <php>
    <min>4.2.0</min>
   </php>
   <pearinstaller>
    <min>1.4.3</min>
   </pearinstaller>
  </required>
 </dependencies>
 <phprelease/>
</package>

The XML file Chiarafoo.xml should be similar to this file:

<role version="1.0">
 <releasetypes>php</releasetypes>
 <installable>1</installable>
 <locationconfig>foo_dir</locationconfig>
 <honorsbaseinstall>1</honorsbaseinstall>
 <unusualbaseinstall />
 <phpfile>1</phpfile>
 <executable />
 <phpextension />
 <config_vars>
  <foo_dir>
   <type>directory</type>
   <default><php_dir/><constant>DIRECTORY_SEPARATOR</constant><text>Foo</text></default>
   <doc>directory where foo files are installed</doc>
   <prompt>PHP foo directory</prompt>
   <group>File Locations</group>
  </foo_dir>
 </config_vars>
</role>

The script in Chiarafoo.php is incredibly simple:

<?php
/**
 * PEAR_Installer_Role_Chiarafoo
 *
 * PHP versions 4 and 5
 *
 * LICENSE: This source file is subject to version 3.0 of the PHP license
 * that is available through the world-wide-web at the following URI:
 * http://www.php.net/license/3_0.txt.  If you did not receive a copy of
 * the PHP License and are unable to obtain it through the web, please
 * send a note to license@php.net so we can mail you a copy immediately.
 *
 * @category   pear
 * @package    Chiarafoo
 * @author     Greg Beaver <cellog@php.net>
 * @copyright  2005 Greg Beaver
 * @license    http://www.php.net/license/3_0.txt  PHP License 3.0
 * @version    CVS: $Id: customroles.xml,v 1.4 2005/11/03 05:06:52 cellog Exp $
 * @link       http://pear.chiaraquartet.net/index.php?package=Chiarafoo
 * @since      File available since Release 0.1.0
 */

/**
 * @category   pear
 * @package    Chiarafoo
 * @author     Greg Beaver <cellog@php.net>
 * @copyright  2005 Greg Beaver
 * @license    http://www.php.net/license/3_0.txt  PHP License 3.0
 * @version    Release: @package_version@
 * @link       http://pear.chiaraquartet.net/index.php?package=Chiarafoo
 * @since      Class available since Release 0.1.0
 */
class PEAR_Installer_Role_Chiarafoo extends PEAR_Installer_Role_Common
{
    /**
     * @param PEAR_Installer
     * @param PEAR_PackageFile_v2
     * @param array file attributes
     * @param string relative path to file in package.xml
     */
    function setup(&$installer, $pkg, $atts, $file)
    {
        // do something special with the installer
    }
}
?>

Since PEAR 1.4.3, nothing else is necessary for a successful implementation of a file role.

The contents of the role's XML file must contain these tags:


The optional <config_vars> tag

This tag is used to define configuration variables that should be added to the installer by this custom file role. Note that the installer will not allow a custom file role to create more than 3 configuration variables. To define configuration variables, create tags with the name of the configuration variable, and then sub-tags defining information about the configuration variable.

These tags are transformed into the PHP array format expected by the PEAR_Config class using an adapted version of Stephan Schmidt's excellent XML_Unserializer class (from the XML_Serializer package). As such, it is easiest to understand the XML format by examining existing configuration variables.

array(
        'password' => array(
            'type' => 'password',
            'default' => '',
            'doc' => '(maintainers) your PEAR account password',
            'prompt' => 'PEAR password (for maintainers)',
            'group' => 'Maintainers',
            ),
        // Advanced
        'verbose' => array(
            'type' => 'integer',
            'default' => PEAR_CONFIG_DEFAULT_VERBOSE,
            'doc' => 'verbosity level
0: really quiet
1: somewhat quiet
2: verbose
3: debug',
            'prompt' => 'Debug Log Level',
            'group' => 'Advanced',
            ),
        'preferred_state' => array(
            'type' => 'set',
            'default' => PEAR_CONFIG_DEFAULT_PREFERRED_STATE,
            'doc' => 'the installer will prefer releases with this state when installing packages without a version or state specified',
            'valid_set' => array(
                'stable', 'beta', 'alpha', 'devel', 'snapshot'),
            'prompt' => 'Preferred Package State',
            'group' => 'Advanced',
            ),
         );

These sample configuration values from the actual PEAR_Config class would translate into this XML:

<config_vars>
 <password>
  <type>password</type>
  <default />
  <doc>(maintainers) your PEAR account password'</doc>
  <prompt>PEAR password (for maintainers)</prompt>
  <group>Maintainers</group>
 </password>
 <verbose>
  <type>integer</type>
  <default><constant>PEAR_CONFIG_DEFAULT_VERBOSE</constant></default>
  <doc>verbosity level
0: really quiet
1: somewhat quiet
2: verbose
3: debug</doc>
  <prompt>Debug Log Level</prompt>
  <group>Advanced</group>
 </verbose>
 <preferred_state>
  <type>set</type>
  <default><constant>PEAR_CONFIG_DEFAULT_PREFERRED_STATE</constant></default>
  <doc>the installer will prefer releases with this state when installing packages without a version or state specified</doc>
  <valid_set>stable</valid_set>
  <valid_set>beta</valid_set>
  <valid_set>alpha</valid_set>
  <valid_set>devel</valid_set>
  <valid_set>snapshot</valid_set>
  <prompt>Preferred Package State</prompt>
  <group>Advanced</group>
 </preferred_state>
</config_vars>

Note that the simple array defining the set converts each value into a separate <valid_set> tag for the preferred_state configuration variable.

The <default> tag's value can accept either a simple string, or three different kinds of tags:

For instance, this example default value:

<default><text0>hi there </text0><constant>PHP_OS</constant><text1> user, your default php_dir is </text1><php_dir/></default>

might convert into something like "hi there Linux user, your default php_dir is /usr/local/lib/php/pear".

Our example Chiarafoo role's foo_dir default value:
<default><php_dir/><constant>DIRECTORY_SEPARATOR</constant><text>Foo</text></default>

might convert into something like "/usr/local/lib/php/Foo" or "C:\php5\pear\Foo".

Note that in order to use multiple <constant> or <text> tags, you must append a numbered suffix as in the <text0> <text1> example above. Only one PEAR configuration variable may be used per default value.

Note that if you use <type>integer</type>, no matter what default value is specified, it will be casted into an integer by PEAR_Config.


Глава 25. Custom File Tasks

For many small library packages, very little customization is needed. Just install and go. package.xml 1.0 is very good at this task. As packages grow in size and complexity, it is often necessary to make slight changes to the contents of files, and occasionally to external components such as databases.

package.xml 1.0 provides a single undocumented system of customizing file contents through the <replace> tag, like so:

<file name="blah.php" role="php">
 <replace from="@token@" to="version" type="package-info"/>
 <replace from="@anothertoken@" to="php_dir" type="pear-config"/>
</file>

This example above would scan the blah.php file at installation, and then use str_replace() to replace all occurences of the string @token@ with the package's version number. Then, it would replace all occurences of the string @anothertoken@ with the value of the user's php_dir configuration variable.

Although powerful, the replace tag is the only customization tag available in package.xml version 1.0. When developing package.xml version 2.0, the replace tag and innovative work of other projects such as Phing became the inspiration for an expanded kind customization called a "task".

Tasks are defined by xml children of a <file> tag. Tasks are implemented by extending the PEAR_Task_Common task.


Creating customized tasks in PHP

Creating a custom task involves creating a class that validates xml, and performs the task when called upon. Tasks can be invoked in two situations: at package-time and at install-time. Each task can control whether it should be called at package-time, install-time, or at both times.

There are two kinds of tasks: simple and multiple. Most tasks are simple tasks. Simple tasks are self-contained: all customization is limited to that file. Multiple tasks are collected during installation and processed fully as a unit after files have been committed to disk, allowing more complex processing.

All simple tasks must define 3 methods, all multiple task must define 4 methods. These are:


validateXml()

This method is called upon package.xml validation and should be used to validate the task's xml content. Upon error, a simple array of format array(CODE, message) must be returned. The code must be one of the following constants, as defined in PEAR/Task/Common.php:

  • PEAR_TASK_ERROR_NOATTRIBS - Attributes were expected, but none were present.

  • PEAR_TASK_ERROR_MISSING_ATTRIB - A specific attribute is not present.

  • PEAR_TASK_ERROR_WRONG_ATTRIB_VALUE - The value of an attribute is incorrect.

  • PEAR_TASK_ERROR_INVALID - Any other error in validation.

The error message should include the file name as defined by $fileAttributes['name'], and include as much useful information about the location of the validation error as possible.

PEAR_PackageFile_v2 $pkg

This is the package.xml object that contains the task.

string|array $xml

The raw parsed content of the task's xml as parsed from package.xml. Tags like <tasks:windowseol> that have no attributes or child elements will be passed an empty string ''. Otherwise, simple text content will be a string, and nested tags/attributes will be passed in as an array. Here is a list of sample xml and their parsed values:

  • <tasks:blah/>

    string("");

  • <tasks:blah>hello
    </tasks:blah>

    string("hello");

  • <tasks:blah>hello
     <tasks:boo/>
    </tasks:blah>

    array('_content' => 'hello', 'tasks:boo' => string(''))

  • <tasks:blah foo="one">
     <tasks:boo/>
    </tasks:blah>

    array('attribs' => array('foo' => 'one'), 'tasks:boo' => string(''))

PEAR_Config $config

This is the current configuration object

array $fileAttributes

The parsed attributes of the <file> tag that encloses this tag. This is guaranteed to contain indices name, specifying the file name, and role, specifying the file role. Other attributes like baseinstalldir may be present but are not required, and so will not be guaranteed to be present for every file.


init()

The init() function is called immediately prior to the startSession() method, and should be used for initialization that is not directly related to file modification. This method may move to another location in the installation process at any time. The logical separation of initialization from task action is important and the order of execution can be depended upon.

string|array $xml

The raw parsed content of the task's xml as parsed from package.xml. Tags like <tasks:windowseol> that have no attributes or child elements will be passed an empty string ''. Otherwise, simple text content will be a string, and nested tags/attributes will be passed in as an array. Here is a list of sample xml and their parsed values:

  • <tasks:blah/>

    string("");

  • <tasks:blah>hello
    </tasks:blah>

    string("hello");

  • <tasks:blah>hello
     <tasks:boo/>
    </tasks:blah>

    array('_content' => 'hello', 'tasks:boo' => string(''))

  • <tasks:blah foo="one">
     <tasks:boo/>
    </tasks:blah>

    array('attribs' => array('foo' => 'one'), 'tasks:boo' => string(''))

array $fileAttributes

The parsed attributes of the <file> tag that encloses this tag. This is guaranteed to contain indices name, specifying the file name, and role, specifying the file role. Other attributes like baseinstalldir may be present but are not required, and so will not be guaranteed to be present for every file.

string|null $lastVersion

This will be set to the string representing the version of the last installed version of this package. This is useful for determining whether the package is being upgraded or is a fresh installation. If the package is being installed for the first time, NULL will be passed in.


Глава 26. Post-installation Scripts

Incomplete documentation

Documentation is not yet complete

The XML format for defining a post-install script in package.xml is documented here. This document describes the required elements for the PHP post-install script itself.


Structure of a post-install script

The post-install script class must contain two methods, one named init(), and the other named run(). The init() method is called at the same time as all other post-install scripts. The run() method is called at the conclusion of each parameter group in order to process the user's responses to queries.


The init() method

PEAR_Config $xml

The current configuration used for installation.

PEAR_PackageFile_v2 $self

The package.xml contents as abstracted by this object.

string|NULL $lastInstalledVersion

The last version of this package that was installed. This is a very important parameter, as it is the only way to determine whether a package is being installed from scratch, or upgraded from a previous version. Using this parameter, it is possible to determine what incremental changes, if any, need to be performed.

V. PEAR Компоненты ядра


Глава 27. Базовые классы PEAR

Центральная часть руководства рассказывает о базовых классах PEAR.


PEAR

Содержание
Введение --  Как использовать базовый класс PEAR (деструкторы, обработка ошибок)
Константы -- Преопределенные константы
PEAR::PEAR() -- constructor (для разработчиков)
PEAR::_PEAR() -- Deconstructor (для разработчиков)
PEAR::getStaticProperty() -- эмулирует статические атрибуты (для разработчиков)
PEAR::registerShutdownFunc() -- назначает функцию для статического класса, которая выполнится при завершении обработки запроса (для разработчиков)
PEAR::isError() -- проверяет является ли входящий параметр объектом PEAR_Error
PEAR::raiseError() -- Create a new PEAR_Error object and optionally specify error-handling instructions
PEAR::setErrorHandling() -- управляет обработкой ошибок в пакетах PEAR
PEAR::expectError() --  добавляет код ошибки для того, чтобы временно включить обработку ошибок
PEAR::popExpect() --  извлекает последний код ошибки из списка ожидаемых ошибок
PEAR::loadExtension() -- OS independant PHP extension load

PEAR предоставляет функции для обработки ошибок и варианты поведения в случае ошибки. Все это дает возможность разработчикам пакетов значительно упростить свою жизнь.

Введение

Введение --  Как использовать базовый класс PEAR (деструкторы, обработка ошибок)

Описание

Базовый класс PEAR предоставляет стандартную функциональность, которая может быть использована большинством классов PEAR. Обычно не требуется создавать объект этого класса, для этого используется наследование от него.

Главные особенности базового класса PEAR:

  • "деструкторы" объектов, срабатывающие при завершении обработки запроса

  • обработка ошибок

"деструкторы" PEAR

Если ваш класс ClassName наследует класс PEAR, то вы можете объявить метод _ClassName (имя класса с префиксом в виде подчеркивания), которые будет вызван по окончанию обработки запроса. Этот метод не является деструктором в том смысле, что вы можете "удалить" объект с его помощью, это метод объекта, который вызывается при завершении работы РНР. См. пример.

Важно!

Для того, чтобы обеспечить работу деструкторов, вы должны создавать объект вашего класса с помощью оператора "=& new". Вот так: this:
$obj =& new MyClass();

Если вы будете использовать "= new", то объект, который будет зарегистрирован - будет его копией на тот момент, когда будет вызван конструктор. Соответственно, "деструктор" будет вызван именно у копии вашего объекта.

Обработка ошибок в PEAR

Базовый класс PEAR также предоставляет инструмент для обработки ошибок более сложных, чем возврат значений true/false или числовых кодов. Ошибка в PEAR - это объект, который является экземпляром класса PEAR_Error или класса, который наследует PEAR_Error.

Один из основных принципов обработки ошибок в PEAR гласит, что ошибки не должны автоматически приводить к выводу на экран пользователя, ошибки должны обрабатываться вообще без какого-либо вывода на экран, если это требуется. Это позволяет обрабатывать ошибки "вежливо", кроме того, это позволяет избежать нежелательного вывода тогда, когда вы используете не HTML, а, например, XML или WML.

Класс ошибок позволяет настроить себя так, что при возникновении ошибки (т.е. при создании экземпляра этого класса) могут выполняться различные действия. Например, вывод сообщения об ошибке, вывод сообщения и прекращение выполнения программы, вывод сообщения с помощью функции trigger_error(), вызов заранее назначенной функции или ничего из вышеперечисленного. Обычно эти параметры указываются в конструкторе PEAR_Error, но все эти параметры являются опциональными и вы можете использовать установки по умолчанию для ошибок, которые используются в классах, наследующих класс PEAR. См. примеры ошибок PEAR и документацию по PEAR_Error для более полной информации.

Примеры

Пример, приведенный ниже, показывает как использовать "деструкторы для бедных" PEAR для того, чтобы создать объект, содержимым которого является файл; объект позволяет добавлять данные в конец и записывает их при окончании обработки запроса:

Замечание: "Деструкторы" PEAR используют функцию register_shutdown_function() в PHP, и в PHP < 4.1 вы не можете выводить ничего в этот момент, если PHP работает с веб-сервером. Поэтому любой вывод в деструкторе будет просто потерян, если PHP используется не в командной строке. В PHP 4.1 и выше уже возможен вывод в деструкторе.

Кроме этого, обратите внимаение на предупреждение о том как следует создавать экземпляр объекта, если вы хотите использовать деструктор.

Следующие примеры иллюстрируют различные пути использования механизма обработки ошибок PEAR.

В примере используется враппер для fsockopen(), который при возникновении ошибки возвращает её код и текст в виде объекта PEAR_Error. Заметьте, что PEAR::isError() используется для того, чтобы определить является ли ошибкой возвращаемое значение.

PEAR_Error в этом примере работает в режиме, при котором ошибка просто возвращается, а её обработка ложится на плечи программиста. Это поведение является поведением по умолчанию.

В следующем примере мы покажем вам как использовать поведение по умолчанию:

Здесь мы сначала меняем поведение по умолчанию на PEAR_ERROR_DIE, а потом, т.к. мы не указываем режим работы в raiseError() (это должно было бы быть 3-м параметром), raiseError() использует поведение по умолчанию и прекращает выполнение скрипта при завершении fsockopen() с ошибкой.

Использование глобальных переменных

Класс PEAR использует несколько глобальных переменных для установок по умолчанию, а список объектов используется для работы "деструкторов". Все глобальные переменные, которые использует класс PEAR носят имя с префиксом _PEAR_.

$_PEAR_default_error_mode

Если не установлен режим по умолчанию, то этот режим будет использован. Должен быть равен PEAR_ERROR_RETURN, PEAR_ERROR_PRINT, PEAR_ERROR_TRIGGER, PEAR_ERROR_DIE или PEAR_ERROR_CALLBACK.

Не меняйте значение это переменной напрямую, используйте PEAR::setErrorHandling()для этого:

$_PEAR_default_error_options

Если используется режим работы PEAR_ERROR_TRIGGER, то должна иметь значение E_USER_NOTICE, E_USER_WARNING или E_USER_ERROR.

Не меняйте значение это переменной напрямую, используйте PEAR::setErrorHandling() для этого:

$_PEAR_default_error_callback

Если при возврате ошибки не был указан параметр options и используется режим обработки ошибок PEAR_ERROR_CALLBACK, то значение этой переменной используется как имя функции, которая будет вызвана при появлении ошибки. Это означает, что вы можете временно переключить режим обработки ошибок без повторного указания имени функции-обработчика. Может иметь ст Here is an example of how you can switch back and forth without specifying the callback function again: роковое значение с именем функции или двухэлементный массив с объектом по индексу 0 и с именем метода по индексу 1.

Еще раз повторим: не меняйте значение этой переменной напрямую, используйте PEAR::setErrorHandling() для этого:

Следующий пример показывает как можно переключаться между режимами обработки ошибок без повторного указания функции-обработчика:

Константы

Константы -- Преопределенные константы

PEAR_ERROR_CALLBACK

Касается обработки ошибок PEAR.

См. PEAR_Error, setErrorHandling()

PEAR_ERROR_DIE

Касается обработки ошибок PEAR.

См. PEAR_Error, setErrorHandling()

PEAR_ERROR_PRINT

Касается обработки ошибок PEAR.

См. PEAR_Error, setErrorHandling()

PEAR_ERROR_RETURN

Касается обработки ошибок PEAR.

См. PEAR_Error, setErrorHandling()

PEAR_ERROR_TRIGGER

Касается обработки ошибок PEAR.

См. PEAR_Error, setErrorHandling()

PEAR::PEAR()

PEAR::PEAR() -- constructor (для разработчиков)

Описание

Если вы хотите использовать функциональность деструкторов PEAR, то вам необходимо вызвать метод $this->PEAR() в конструкторе вашего класса.

Параметр

  • string $errorClass - имя класса ошибок, который будет использоваться.

Заметка

Эта функция может быть вызвана статически.

PEAR::_PEAR()

PEAR::_PEAR() -- Deconstructor (для разработчиков)

Описание

Does nothing right now, but is included for forward compatibility, so subclass destructors should always call it.

PEAR::getStaticProperty()

PEAR::getStaticProperty() -- эмулирует статические атрибуты (для разработчиков)

Описание

Если ваш класс является статическим, то вам, вероятно, понадобятся статические атрибуты. Вы можете эмулировать их с помощью этого метода примерно так:
$myVar = &PEAR::getStaticProperty('myVar');
Использовать ссылку обязательно, иначе атрибут не будет статическим!

Параметр

  • string $class - имя вашего класса, в котором вы вызываете getStaticProperty()

  • string $var - имя статического атрибута

Возвращаемое значение

mixed - ссылку на атрибут. Если атрибут не был инициализирован, то ему автоматически будет присвоено значение NULL.

PEAR::registerShutdownFunc()

PEAR::registerShutdownFunc() -- назначает функцию для статического класса, которая выполнится при завершении обработки запроса (для разработчиков)

Описание

Указанная функция вызывается перед тем, как интерпретатор заканчивает работу.

Параметр

  • array $func - имя класса и его метод.

  • array $var - аргументы вызываемой функции. Параметры передаются функции в том порядке, в котором они входят в массив.

PEAR::isError()

PEAR::isError() -- проверяет является ли входящий параметр объектом PEAR_Error

Описание

isError() проверяет является ли переменная объектом PEAR_Error.

Параметр

  • mixed $data - переменная, которая проверяется.

Возвращаемое значение

mixed - возвращает TRUE, если переменная является объектом PEAR_Error

PEAR::raiseError()

PEAR::raiseError() -- Create a new PEAR_Error object and optionally specify error-handling instructions

Описание

raiseError()

Параметр

string $message

Error message string or PEAR_Error object. The default message is unknown error if left blank.

integer $code

Error code. It is recommended to use an error code for even the simplest errors, in order to simplify error handling and processing.

integer $mode

Error mode. This is one of PEAR_ERROR_RETURN, PEAR_ERROR_PRINT, PEAR_ERROR_TRIGGER, PEAR_ERROR_DIE, PEAR_ERROR_CALLBACK, or PEAR_ERROR_EXCEPTION. See setErrorHandling() for detailed information and examples of the meaning of these constants.

mixed $options

Error options. This depends on the value of $mode, and is documented in setErrorHandling().

mixed $userinfo

Optional user information. This can be used to store any error-specific information, and has an unspecified format.

string $error_class

Error class name to use as the error object. The default error class is PEAR_Error. Use this parameter to specify another class to use, such as a custom class extending PEAR_Error

boolean $skipmsg

Use this parameter if you are using a custom class that does not accept an error message in its constructor. Never use this parameter without the $error_class parameter - it will not work.

Возвращаемое значение

A PEAR_Error object is returned, unless PEAR_ERROR_DIE terminates execution or a PEAR_ERROR_EXCEPTION is never handled.

PEAR::setErrorHandling()

PEAR::setErrorHandling() -- управляет обработкой ошибок в пакетах PEAR

Описание

setErrorHandling() может быть вызвана статически и как метод объекта. При статическом вызове setErrorHandling() устанавливает поведение по умолчанию для всех объектов PEAR. При вызове метода объекта setErrorHandling() устанавливает поведение по умолчанию только для этого объекта.

Параметр

  • integer $mode - имеет значение, равное одной из следующих констант:

    • PEAR_ERROR_RETURN если происходит ошибка, то возвращается объект PEAR_Error.

    • PEAR_ERROR_PRINT похожа на PEAR_ERROR_RETURN, но при этом выводится сообщение об ошибке.

    • PEAR_ERROR_TRIGGER похожа на PEAR_ERROR_RETURN, но при этом дополнительно вызывается функция trigger_error().

    • PEAR_ERROR_DIE - выполнение прерывается и выводится сообщение об ошибке.

    • PEAR_ERROR_CALLBACK - при возникновении ошибки вызывается указанная функция-обработчик. Функция должна принимать объект класса PEAR_Error в качестве параметра.

  • mixed $options - значения опций зависят от параметра $mode

    • PEAR_ERROR_PRINT и PEAR_ERROR_DIE поддерживают опциональный параметр - строку для функции printf(), для форматирования вывода ошибки.

    • PEAR_ERROR_TRIGGER требует указания уровня ошибки: ( E_USER_NOTICE, E_USER_WARNING или E_USER_ERROR).

    • PEAR_ERROR_CALLBACK требует указания имени функции, которая будет вызвана.

PEAR::expectError()

PEAR::expectError() --  добавляет код ошибки для того, чтобы временно включить обработку ошибок

Описание

Этот метод используется для того, чтобы указать какие ошибки вы ожидаете получить. Ожидаемые ошибки всегда возвращаются в режиме PEAR_ERROR_RETURN. Ожидаемые коды ошибок хранятся в стеке, а этот метод заносит в него новый элемент. Список ожидаемых ошибок используется до тех пор, пока они не извлечены из стека методом popExpect().

Параметр

  • mixed $errorCode - ожидаемый код ошибки PEAR_Error или массив кодов. Если указано значение '*' - ожидается любая ошибка.

Возвращаемое значение

integer - размер стека кодов ошибок.

Заметка

Эта функция не должна вызываться статически.

См. также

popExpect()

PEAR::popExpect()

PEAR::popExpect() --  извлекает последний код ошибки из списка ожидаемых ошибок

Описание

Этот метод извлекает последний элемент из стэка кодов ожидаемых ошибок.

Возвращаемое значение

mixed - код ошибки, который был извлечен или массив кодов, которые были извлечены

Заметка

Эта функция не должна вызываться статически.

См. также

expectError()

PEAR::loadExtension()

PEAR::loadExtension() -- OS independant PHP extension load

Описание

Loads an extension by name

Параметр

string $ext

The case-sensitive name of the PHP extension without filename suffix or php_ prefix.

Возвращаемое значение

boolean - returns TRUE, if extension could be loaded

Заметка

Эта функция может быть вызвана статически.


PEAR_Error

Содержание
PEAR_Error::addUserInfo() -- добавляет пользовательскую информацию
PEAR_Error::getCallback() -- получает имя функции, вызываемой при ошибке
PEAR_Error::getCode() -- получает код ошибки
PEAR_Error::getMessage() -- получает текст ошибки
PEAR_Error::getMode() -- получает режим обработки ошибок
PEAR_Error::getDebugInfo() -- получает отладочную информацию
PEAR_Error::getType() -- получает тип ошибки
PEAR_Error::getUserInfo() -- получает дополнительную пользовательскую информацию
PEAR_Error::PEAR_Error() -- constructor
PEAR_Error::toString() -- превращает объект в строку

PEAR_Error - это объект, которые создается каждой функцией PEAR в случае возникновения ошибки. Он предоставляется информацию о том, почему функция завершилась с ошибкой.

Как именно вы получаете объект - зависит от PEAR::SetErrorHandling()

PEAR_Error::addUserInfo()

PEAR_Error::addUserInfo() -- добавляет пользовательскую информацию

Описание

Добавляет пользовательскую информацию в объект ошибки.

Параметр

  • string - пользовательская информация

Заметка

Эта функция не должна вызываться статически.

PEAR_Error::getCallback()

PEAR_Error::getCallback() -- получает имя функции, вызываемой при ошибке

Описание

Возвращает имя функции, которая вызывается при возврате объекта PEAR_Error.

Возвращаемое значение

string - имя функции

Заметка

Эта функция не должна вызываться статически.

PEAR_Error::getCode()

PEAR_Error::getCode() -- получает код ошибки

Описание

Возвращает код ошибки, который указан в объекте PEAR_Error.

Возвращаемое значение

integer - код ошибки

Заметка

Эта функция не должна вызываться статически.

PEAR_Error::getMessage()

PEAR_Error::getMessage() -- получает текст ошибки

Описание

Возвращает текст ошибки,который указан в объекте PEAR_Error.

Возвращаемое значение

string - текст ошибки

Заметка

Эта функция не должна вызываться статически.

PEAR_Error::getMode()

PEAR_Error::getMode() -- получает режим обработки ошибок

Описание

Возвращает режим обработки ошибок, который учитывается при создании объекта PEAR_Error.

Возвращаемое значение

integer - режим обработки ошибок

Заметка

Эта функция не должна вызываться статически.

PEAR_Error::getDebugInfo()

PEAR_Error::getDebugInfo() -- получает отладочную информацию

Описание

Возвращает отладочную информацию об ошибке

Возвращаемое значение

string - отладочная информация об ошибке

Заметка

Эта функция не должна вызываться статически.

PEAR_Error::getType()

PEAR_Error::getType() -- получает тип ошибки

Описание

Возвращает имя класса объекта ошибки.

Возвращаемое значение

string - имя класса

Заметка

Эта функция не должна вызываться статически.

PEAR_Error::getUserInfo()

PEAR_Error::getUserInfo() -- получает дополнительную пользовательскую информацию

Описание

Возвращает дополнительную информацию об ошибке

Возвращаемое значение

string - информация об ошибке

Заметка

Эта функция не должна вызываться статически.

PEAR_Error::PEAR_Error()

PEAR_Error::PEAR_Error() -- constructor

Описание

Constructor

Параметр

  • string $message - текст ошибки. Короткое описание возникшей проблемы.

  • string $code - код ошибки.

  • integer $mode - режим обработки ошибок.

  • mixed $options - дополнительные опции режима обработки ошибок

  • string $userinfo - строка с дополнительной инфорамацией об ошибке

Заметка

Эта функция может быть вызвана статически.

PEAR_Error::toString()

PEAR_Error::toString() -- превращает объект в строку

Описание

Возвращает строковое представление объекта.

Возвращаемое значение

string - строка с содержанием объекта ошибки

Заметка

Эта функция не должна вызываться статически.


PEAR_ErrorStack

Содержание
Introduction to using PEAR_ErrorStack for advanced error handling --  Using PEAR_ErrorStack to do both simple and advanced error handling
constructor PEAR_ErrorStack::PEAR_ErrorStack() -- Set up a new error stack instance
PEAR_ErrorStack::getErrorMessage() -- Standard error message generation callback
PEAR_ErrorStack::getErrorMessageTemplate() -- Standard Error Message Template generator from error code
PEAR_ErrorStack::getErrors() -- Retrieve all errors since last purge
PEAR_ErrorStack::getFileLine() -- Standard file/line number/function/class context callback
PEAR_ErrorStack::getMessageCallback() -- Get an error code => error message mapping callback
PEAR_ErrorStack::hasErrors() -- Determine whether there are any errors on the stack
PEAR_ErrorStack::pop() -- Pop an error off of the error stack
PEAR_ErrorStack::popCallback() -- Remove a callback from the error callback stack
PEAR_ErrorStack::push() -- Add an error to the stack
PEAR_ErrorStack::pushCallback() -- Set an error Callback If set to a valid callback, this will be called every time an error is pushed onto the stack. The return value will be used to determine whether to allow an error to be pushed or logged.
PEAR_ErrorStack::raiseError() -- emulate PEAR::raiseError()
PEAR_ErrorStack::setContextCallback() --  Set a callback that generates context information (location of error) for an error stack
PEAR_ErrorStack::setDefaultCallback() --  Sets a default callback to be used by all error stacks
PEAR_ErrorStack::setDefaultLogger() --  Set up a PEAR::Log object for all error stacks that don't have one
PEAR_ErrorStack::setErrorMessageTemplate() -- Set the Error Message Template array
PEAR_ErrorStack::setLogger() --  Set up a PEAR::Log object for this error stack
PEAR_ErrorStack::setMessageCallback() --  Set an error code => error message mapping callback
PEAR_ErrorStack::singleton() -- Return a single error stack for this package.
PEAR_ErrorStack::staticGetErrors() --  Get a list of all errors since last purge, organized by package
PEAR_ErrorStack::staticHasErrors() --  Determine whether there are any errors on any error stack
PEAR_ErrorStack::staticPop() --  Static version of pop()
PEAR_ErrorStack::staticPopCallback() -- Remove a callback from every error callback stack
PEAR_ErrorStack::staticPush() --  Static version of push()
PEAR_ErrorStack::staticPushCallback() --  Set an error Callback for every package's error stack
PEAR_ErrorStack::_log() -- Log an error using PEAR::Log
Package PEAR_ErrorStack Constants -- Constants defined in and used by PEAR_ErrorStack

PEAR_ErrorStack is an experimental error raising and handling implementation for PEAR that is designed to replace PEAR_Error when it has stabilized. PEAR_ErrorStack is both backwards compatible with PEAR_Error and forward compatible with PHP 5's PEAR_Exception class. There are many other features, all described in the Introduction.

Usage:
1      // global error stack
2      $global_stack = &PEAR_ErrorStack::singleton('MyPackage');
3      // local error stack
4      $local_stack = new PEAR_ErrorStack('MyPackage');

Introduction to using PEAR_ErrorStack for advanced error handling

Introduction to using PEAR_ErrorStack for advanced error handling  --  Using PEAR_ErrorStack to do both simple and advanced error handling

Introduction

This class is available as part of the PEAR package. Features include:

  • Fully unit-tested and documented

  • blazingly fast - blows PEAR_Error out of the water

  • Package-specific errors

  • Error levels (notice/warning/error/exception)

  • Error context data is saved separate from error message

  • Error cascading - parent errors can be specified

  • Dynamic error message generation allows generation of multiple and distinct error messages from the same error object

  • Sophisticated callbacks are available for error message generation, error context generation, and error handling functionality, see Error Context Display, Custom Error Message Generation, and controlling error generation

PEAR_ErrorStack implements error raising and handling using a stack pattern. This has tremendous advantages over the PEAR_Error Implementation. PEAR_Error centralizes all error creation and handling in the constructor of the PEAR_Error object. Once an object has been created, all handling must have been completed, either through checking the return value of a method, or through a single global callback. In addition, it is nearly impossible to determine the source of an error, and the baggage of all of the PEAR base class's bulky, slow methods accompanies every error creation.

<?php
// traditional PEAR_Error usage
require_once 'PEAR.php';
class myobj
{
    // there is no way to know where $err comes from
    function errorCallback($err)
    {
        $this->display($err->getMessage());
        $this->log($err->getMessage());
    }

    function log($msg)
    {
        error_log($msg, 3, 'somefile.log')
    }

    function display($msg)
    {
        echo $msg . '<br />';
    }
}

$myobj = new myobj;

// using a callback
PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array(&$myobj, 'errorCallback'));

$ret = SomePackage::doSomething();
if (PEAR::isError($ret)) {
    // do some handling - this error is also displayed and logged
}
PEAR::pushErrorHandling(PEAR_ERROR_RETURN);

$ret = SomePackage::doSomething();
if (PEAR::isError($ret)) {
    // do some handling - this error is not displayed or logged
}
PEAR::popErrorHandling();
?>

The PEAR_ErrorStack class has built in knowledge of the Log package, can easily differentiate and even automatically re-package errors with little to no difficulty.

<?php
// PEAR_ErrorStack error handling
require_once 'PEAR/ErrorStack.php';
require_once 'Log.php';
define('MYPACKAGE_ERROR_DBERROR', 1);
class myobj
{
    var $_stack;
    function myobj()
    {
        $this->_stack = &PEAR_ErrorStack::singleton('MyPackage');
    }

    function errorCallback($err)
    {
        switch($err['package']){
            case 'MyPackage':
                // tell the error stack to log the error only
                // it will not be pushed onto the stack
                return PEAR_ERRORSTACK_LOG;
                break;
            case 'InternalDbPackage':
                // re-package these errors as a mypackage error fit
                // for enduser consumption
                $this->_stack->push(MYPACKAGE_ERROR_DBERROR, 'error',
                    array('dbmessage' => $err['message'],
                          'dbcode' => $err['code'],
                          'We are having Connection problems, please' .
                          'try again in a few moments'),
                    '', $err); // include the error as re-packaged
                // tell the internal DB error stack to ignore this error,
                // as if it never happened
                return PEAR_ERRORSTACK_IGNORE;
                break;
        } // switch
    }
}

$myobj = &new myobj;
// separate error stacks for my package, and the internal DB package
$dbstack = &PEAR_ErrorStack::singleton('InternalDbPackage');
$mystack = &PEAR_ErrorStack::singleton('MyPackage');
// set up a file log using PEAR::Log
$log = &Log::Factory('file', 'somefile.log', 'MyPackage error log');
$mystack->setLogger($log);
// set up a default log to use for all error stacks
PEAR_ErrorStack::setDefaultLogger($log);

// any errors returned by MyPackage are logged
$ret = SomePackage::doSomething();

// Note that $ret need not be checked for any error condition - errors are
// totally separate from code
if ($dbstack->hasErrors()) {
    var_dump($dbstack->getErrors();
}

// sets a default callback for all errors
PEAR_ErrorStack::setDefaultCallback(array(&$myobj, 'errorCallback'));

// any db errors are transparently repackaged as
// user-friendly MyPackage errors now
$ret = SomePackage::doSomething();

?>

Why write a new error-handling routine when PEAR_Error already exists? There are several problems with PEAR_Error. Although an error message is present in an error class, processing this error message automatically is excessively difficult for computers. In addition, the error message cannot easily be translated once it has been placed into the PEAR_Error. There is also no standard facility for storing error-related data in the error class. On top of error message-related issues, there is no way to automatically determine which package a PEAR_Error object comes from, or the severity of an error. Fatal errors look exactly the same as non-fatal errors.

The largest flaw with PEAR_Error object is the single-error type design. Every PEAR_Error object is just a PEAR_Error object. There is no differentiating between the severity of an error, or its origin. The only way to determine the severity is to use PEAR_ERROR_TRIGGER and E_USER_NOTICE/E_USER_WARNING/E_USER_ERROR constants from php's trigger_error. But using this functionality does not justify 900 lines of code, simply because trigger_error() is built into PHP itself!

Now, to start using your newly created error objects, change all of your PEAR::raiseError() or PEAR::throwError() calls from this...

<?php
require_once 'PEAR.php';
// old way:
$error_specific_info = 'bad';
$e = PEAR::raiseError("error message - very " . $error_specific_info .
    " way to do things", MYPACKAGE_ERROR_FOO);
// another old way:
$e = PEAR::throwError("error message - very " . $error_specific_info .
    " way to do things", MYPACKAGE_ERROR_FOO);
?>

...to something like this:

<?php
require_once 'PEAR/ErrorStack.php';
// new way
// version 1: stack instance access
$stack = &PEAR_ErrorStack::singleton('MyPackage');
$stack->push(MYPACKAGE_ERROR_DBERROR, 'error',
    array('query' => $query, 'dsn' => $dsn),
    'Critical Database Error: Contact Administrator immediately');
// version 2: static singleton access (slightly slower)
PEAR_ErrorStack::staticPush('MyPackage', MYPACKAGE_ERROR_DBERROR, 'error',
    array('query' => $query, 'dsn' => $dsn),
    'Critical Database Error: Contact Administrator immediately');
?>

For basic use, this is all that is needed to use the PEAR_ErrorStack package in place of PEAR_Error.

Advanced Features

Error Context Display

In some cases, you may want to customize error generation. For instance, for many exceptions, it is useful to include file, line number, and class/function context information in order to trace an error. A default option is available which will be sufficient for most cases, and that is PEAR_ErrorStack::getFileLine().

Not all package errors occur in the PHP source file. For instance, compiling template engines errors can occur in the template source files. Database errors can occur in the text of a query, or internal to the database server. Internet package errors can occur on another server. All of this information can be included in an error message using a context grabbing callback.

<?php
require_once 'PEAR/ErrorStack.php';
class DatabaseClass
{
    var $_dbError;
    var $_dbErrorMsg;
    var $_dbQuery;
    var $_dbPos;
    /**
     * Context grabber for the Database package
     * @param integer Error Code
     * @param array   Error parameters passed into {@link PEAR_ErrorStack::push()}
     * @param array   Output of debug_backtrace() (not used in this callback)
     */
    function getErrorContext($code, $params, $backtrace)
    {
        $context = array(
            'errorcode' => $this->_dbError,
            'errormsg' => $this->_dbErrorMsg,
            'query' => $this->_dbQuery,
            'pos' => $this->_dbPos,
        );
        return $context;
    }
}
$db = new DatabaseClass;
PEAR_ErrorStack::staticSetContextCallback('Database', array(&$db, 'getErrorContext'));
?>

The context information is formatted to be easily processed by an external application. If you wish context information to be in the error message, the error message callback should be used to add the information in a human-readable format to the error message, as described in the next section.

Custom Error Message Generation

There are three methods of PEAR_ErrorStack designed for use with generating error messages efficiently. To use them, you must do one of three things:

  • Call PEAR_ErrorStack::setErrorMessageTemplate(), and set an array mapping error codes to error message templates, like so:

    <?php
    define('ERROR_ONE', 1);
    define('ERROR_TWO', 2);
    define('ERROR_THREE', 3);
    define('ERROR_FOUR', 4);
    require_once 'PEAR/ErrorStack.php';
    $stack = &PEAR_ErrorStack::singleton('mypackage');
    $messages = array(
        ERROR_ONE => 'The gronk number %num% dropped a %thing%',
        ERROR_TWO => 'The %list% items were missing',
        ERROR_THREE => 'I like chocolate, how about %you%?',
        ERROR_FOUR => 'and a %partridge% in a pear %tree%',
    );
    $stack->setErrorMessageTemplate($messages);
    ?>

    Substitution is done using str_replace, and is very simple. Basically, if a variable name is enclosed in percent signs (%), it will be replaced with the value passed in the associative array. If an array
    array('varname' => 'value');
    is passed to either method, all occurrences of %varname% will be replaced by value.

    In addition, if values are objects, the methods will search for a method named "__toString()" and if found, will use that to convert the object to a string. If an array of strings is passed in, they will be joined by commas.
    <?php
    array('varname' => array('first', 'second', 'third'));
    // this will become 'first, second, third'
    ?>

  • Call PEAR_ErrorStack::setMessageCallback(), and set a custom error message generating function or method. This is probably the best option for the majority of complex situations, as it allows users to override or even extend the existing error message callback using PEAR_ErrorStack::getMessageCallback(). For example:
    <?php
    require_once 'PEAR/ErrorStack.php';
    class foo
    {
        var $_oldcallback;
        function callback(&$stack, $err)
        {
            $message = call_user_func_array($this->_oldcallback, array(&$stack, $err));
            $message .= "File " . $err['context']['file'];
            return $message;
        }
    }
    $a = new foo;
    $stack = &PEAR_ErrorStack::singleton('otherpackage');
    $a->_oldcallback = $stack->getMessageCallback('otherpackage');
    $stack->setMessageCallback(array(&$a, 'callback'));
    ?>

  • Extend PEAR_ErrorStack with your own class, and override PEAR_ErrorStack::getErrorMessageTemplate() or PEAR_ErrorStack::getErrorMessage(). To guarantee that this class will be used by other packages/applications, use this code right after the class declaration:

    <?php
    PEAR_ErrorStack::singleton('mypackage', false, null, 'MyPEAR_ErrorStack');
    ?>

Controlling error generation

There are many scenarios in which fine-grained control over error raising is absolutely necessary. A generic error handling callback means that every single error raised will be handled in the same error callback. Although PEAR_ErrorStack is designed to operate with independent callbacks for each package, generic error handling is possible through the PEAR_ErrorStack::staticPushCallback() method. This is no different from PEAR_Error's PEAR_ERROR_CALLBACK error handling mode.

PEAR_ErrorStack's real strength comes from the callback itself. PEAR_Error's callback has no actual effect on the error message - all error handling must happen in the callback method or function itself. PEAR_ErrorStack's callback can influence the error through the use of three constants:

PEAR_ERRORSTACK_IGNORE informs the stack to ignore the error, as if it never occurred. The error will be neither logged, nor pushed on the stack. It will, however, be returned from PEAR_ErrorStack::push()

PEAR_ERRORSTACK_PUSH informs the stack to push the error onto the error stack, but not to log the error.

PEAR_ERRORSTACK_LOG informs the stack not to push the error onto the error stack, but only to log the error.

<?php
define('ERROR_CODE_ONE',1);
define('ERROR_CODE_TWO',2);
define('ERROR_CODE_THREE',3);
require_once 'PEAR/ErrorStack.php';
require_once 'Log.php';
function somecallback($err)
{
    switch($err['code']){
        case ERROR_CODE_ONE:
                return PEAR_ERRORSTACK_IGNORE;
                break;
        case ERROR_CODE_TWO:
                return PEAR_ERRORSTACK_PUSH;
                break;
        case ERROR_CODE_THREE:
                return PEAR_ERRORSTACK_LOG;
                break;
    } // switch
}
$log = &Log::factory('display');
$stack = &PEAR_ErrorStack::singleton('mypackage');
$stack->setLogger($log);
$stack->pushCallback('somecallback');
$stack->push(ERROR_CODE_ONE);
$stack->push(ERROR_CODE_TWO);
$stack->push(ERROR_CODE_THREE);
var_dump(PEAR_ErrorStack::staticGetErrors());

// simulate PEAR_ERROR_CALLBACK, with specific callback for mypackage
// every other package will only log errors, only mypackage's errors
// are pushed on the stack, conditionally
class myclass {
    function acallback($err)
    {
        return PEAR_ERRORSTACK_LOG;
    }
}
$stack2 = PEAR_ErrorStack::singleton('anotherpackage');
$stack3 = &PEAR_ErrorStack::singleton('thirdpackage');
PEAR_ErrorStack::setDefaultCallback(array('myclass', 'acallback'));
?>

Repackaging errors from one package to another

The most obvious usage for an error callback involves a common scenario in many user-level applications that use system-level packages. If you write a Content Management System (CMS) with the PEAR DB package, it is usually a bad idea to display database-level errors when a user clicks on a link to add a message to a forum. PEAR_ErrorStack can be used to repackage this error as a MyPackage error.

<?php
define('MYPACKAGE_ERROR_DBDOWN',1);
require_once 'PEAR/ErrorStack.php';
function repackage($err)
{
    if ($err['package'] == 'DB') {
        $mystack = &PEAR_ErrorStack::singleton('mypackage');
        $mystack->push(MYPACKAGE_ERROR_DBDOWN, 'error', array('olderror' => $err));
        // ignore the DB error, but save it in the mypackage error, for logging
        return PEAR_ERRORSTACK_IGNORE;
    }
}
?>

Emulating the @ operator

One of the difficult-to-use strengths of PEAR_Error involves the PEAR::expectError() method. With regular PHP errors, it is possible to silence them using the @ operator like so:

<?php
@file_get_contents();
?>

Emulating this behavior with PEAR_ErrorStack is simple.

<?php
define('ERROR_CODE_SOMETHING', 1);
require_once 'PEAR/ErrorStack.php';
function silence($err)
{
    // ignore all errors
    return PEAR_ERRORSTACK_IGNORE;
}
$stack = &PEAR_ErrorStack::singleton('mypackage');
$stack->pushCallback('silence');
$stack->push(ERROR_CODE_SOMETHING);
?>

PEAR_ErrorStack can take this one step further, and only log errors or only put errors on the error stack, using the other two constants. Finally, particular errors can be singled out, and all others ignored.

<?php
define('SOMEPACKAGE_ERROR_THING', 1);
require_once 'PEAR/ErrorStack.php';
function silenceSome($err)
{
    if ($err['package'] != 'somepackage') {
        // ignore all errors from other packages
        return PEAR_ERROR_IGNORE;
    }
    if ($err['code'] != SOMEPACKAGE_ERROR_THING) {
        // ignore all other error codes
        return PEAR_ERRORSTACK_IGNORE;
    }
}
$stack = &PEAR_ErrorStack::singleton('mypackage');
$stack->pushCallback('silenceSome');
$stack->push(ERROR_CODE_SOMETHING);
?>

Backwards compatibility with PEAR_Error, Forward compatibility with PHP 5 Exception and PEAR_Exception

PEAR_ErrorStack can also be programmed to automatically raise a PEAR_Error using PEAR::raiseError(), simply pass in true to the PEAR_Error compatibility like so:

<?php
require_once 'PEAR/ErrorStack.php';
$stack = &PEAR_ErrorStack::singleton('mypackage', false, false, true);
?>

PEAR_ErrorStack can coordinate with the new PEAR_Exception class to convert into an exception with this code: You can set the exception class name that will be returned using the following code:

<?php
require_once 'PEAR/ErrorStack.php';
require_once 'PEAR/Exception.php';
$stack = &PEAR_ErrorStack::singleton('mypackage');
$stack->push(1, 'test error');
throw new PEAR_Exception('did not work', $stack->pop());
?>

constructor PEAR_ErrorStack::PEAR_ErrorStack()

constructor PEAR_ErrorStack::PEAR_ErrorStack() -- Set up a new error stack instance

Backwards Compatibility Warning

Внимание

As of PEAR 1.3.2, PEAR_ErrorStack no longer instantiates and returns an Exception object in PHP5, and the last parameter has been removed. Code that relies upon this behavior will break.

Описание

Creates a new private PEAR_ErrorStack. To access a universal stack, use PEAR_ErrorStack::singleton()

Параметр

string $package

name of the package this error stack represents

callback $msgCallback

callback used for error message generation

callback $contextCallback

callback used for context generation, defaults to getFileLine()

boolean $throwPEAR_Error

string $exceptionClass

exception class to instantiate if in PHP 5

Throws

throws no exceptions thrown

Заметка

Эта функция не должна вызываться статически.

PEAR_ErrorStack::getErrorMessage()

PEAR_ErrorStack::getErrorMessage() -- Standard error message generation callback

Описание

This method may also be called by a custom error message generator to fill in template values from the params array, simply set the third parameter to the error message template string to use

The special variable %__msg% is reserved: use it only to specify where a message passed in by the user should be placed in the template, like so:

Error message: %msg% - internal error

If the message passed like so:

<?php
$stack->push(ERROR_CODE, 'error', array(), 'server error 500');
?>

The returned error message will be "Error message: server error 500 - internal error"

Параметр

PEAR_ErrorStack &$stack

array $err

string|false $template

Pre-generated error message template

Throws

throws no exceptions thrown

Заметка

Эта функция должна вызываться статически.

PEAR_ErrorStack::getErrorMessageTemplate()

PEAR_ErrorStack::getErrorMessageTemplate() -- Standard Error Message Template generator from error code

Описание

Standard Error Message Template generator from error code

Параметр

mixed $code

Throws

throws no exceptions thrown

Заметка

Эта функция не должна вызываться статически.

PEAR_ErrorStack::getErrors()

PEAR_ErrorStack::getErrors() -- Retrieve all errors since last purge

Описание

Retrieve all errors since last purge, or filter all errors and only return errors of a particular error level, leaving the rest on the stack.

Параметр

boolean $purge

set in order to empty the error stack

string $level

Level name to check for a particular severity. Use this to determine whether only a particular class of errors has occurred, such as whether any warnings have occurred (errors will be ignored)

Throws

throws no exceptions thrown

Заметка

Эта функция не должна вызываться статически.

PEAR_ErrorStack::getFileLine()

PEAR_ErrorStack::getFileLine() -- Standard file/line number/function/class context callback

Описание

This function uses a backtrace generated from debug_backtrace and so will not work at all in PHP < 4.3.0. The frame should reference the frame that contains the source of the error.

Параметр

array $code

Results of debug_backtrace()

unused $params

integer $backtrace

backtrace frame.

Возвращаемое значение

returns either array('file' => file, 'line' => line, 'function' => function name, 'class' => class name) or if this doesn't work, then false

Throws

throws no exceptions thrown

Заметка

Эта функция должна вызываться статически.

PEAR_ErrorStack::getMessageCallback()

PEAR_ErrorStack::getMessageCallback() -- Get an error code => error message mapping callback

Описание

This method returns the current callback that can be used to generate error messages

Возвращаемое значение

returns Callback function/method or false if none

Throws

throws no exceptions thrown

Заметка

Эта функция не должна вызываться статически.

PEAR_ErrorStack::hasErrors()

PEAR_ErrorStack::hasErrors() -- Determine whether there are any errors on the stack

Описание

Determine whether there are any errors on the stack

Параметр

string $level

Level name to check for a particular severity. Use this to determine whether only a particular class of errors has occurred, such as whether any warnings have occurred (errors will be ignored)

Throws

throws no exceptions thrown

Заметка

Эта функция не должна вызываться статически.

PEAR_ErrorStack::pop()

PEAR_ErrorStack::pop() -- Pop an error off of the error stack

Описание

Pop an error off of the error stack

Throws

throws no exceptions thrown

Заметка

since 0.4alpha it is no longer possible to specify a specific error level to return - the last error pushed will be returned instead.

Заметка

Эта функция не должна вызываться статически.

PEAR_ErrorStack::popCallback()

PEAR_ErrorStack::popCallback() -- Remove a callback from the error callback stack

Описание

Remove a callback from the error callback stack

Throws

throws no exceptions thrown

См. также

see PEAR_ErrorStack::pushCallback()

Заметка

Эта функция не должна вызываться статически.

PEAR_ErrorStack::push()

PEAR_ErrorStack::push() -- Add an error to the stack

Backwards Compatibility Warning

Внимание

As of PEAR 1.3.2, PEAR_ErrorStack no longer instantiates and returns an Exception object in PHP5. Code that relies upon this behavior will break.

Описание

If the message generator exists, it is called with 2 parameters.

  • the current Error Stack object

  • an array that is in the same format as an error. Available indices are 'code', 'package', 'time', 'params', 'level', and 'context'

Next, if the error should contain context information, this is handled by the context grabbing method. Finally, the error is pushed onto the proper error stack

Параметр

integer $code

Package-specific error code

string $level

Error level. This is NOT spell-checked

array $params

associative array of error parameters

string $msg

Error message, or a portion of it if the message is to be generated

array $repackage

If this error re-packages an error pushed by another package, place the array returned from pop() in this parameter

array $backtrace

Protected parameter: use this to pass in the http://www.php.net/manual-lookup.php?pattern=debug_backtrace that should be used to find error context.

Возвращаемое значение

returns if compatibility mode is on, a PEAR_Error is also thrown. If the class Exception exists, then one is returned to allow code like:
<?php
1      throw ($stack->push(MY_ERROR_CODE, 'error', array('username' => 'grob')));
?>

The errorData property of the exception class will be set to the array that would normally be returned. If a PEAR_Error is returned, the userinfo property is set to the array

Otherwise, an array is returned in this format:
<?php
1      array(
2         'code' => $code,
3         'params' => $params,
4         'package' => $this->_package,
5         'level' => $level,
6         'time' => time(),
7         'context' => $context,
8         'message' => $msg,
9      //['repackage' => $err] repackaged error array
10     );
?>

Throws

No exceptions thrown.

Заметка

Эта функция не должна вызываться статически.

PEAR_ErrorStack::pushCallback()

PEAR_ErrorStack::pushCallback() -- Set an error Callback If set to a valid callback, this will be called every time an error is pushed onto the stack. The return value will be used to determine whether to allow an error to be pushed or logged.

Описание

The return value must be one of the PEAR_ERRORSTACK_* constants.

This functionality can be used to emulate PEAR's pushErrorHandling, and the PEAR_ERROR_CALLBACK mode, without affecting the integrity of the error stack or logging

Параметр

string|array $cb

Throws

throws no exceptions thrown

Заметка

Эта функция не должна вызываться статически.

PEAR_ErrorStack::raiseError()

PEAR_ErrorStack::raiseError() -- emulate PEAR::raiseError()

Описание

See PEAR::raiseError()

Throws

No exceptions thrown.

Заметка

Эта функция может быть вызвана статически.

PEAR_ErrorStack::setContextCallback()

PEAR_ErrorStack::setContextCallback()  --  Set a callback that generates context information (location of error) for an error stack

Описание

This method sets the callback that can be used to generate context information for an error. Passing in NULL will disable context generation and remove the expensive call to debug_backtrace()

Параметр

mixed $contextCallback

A valid callback as defined by is_callable()

Throws

No exceptions thrown.

Заметка

Эта функция не должна вызываться статически.

PEAR_ErrorStack::setDefaultCallback()

PEAR_ErrorStack::setDefaultCallback()  --  Sets a default callback to be used by all error stacks

Описание

This method sets the callback that can be used to generate error messages for a singleton

Параметр

array|string $callback

Callback function/method

Throws

No exceptions thrown.

Заметка

Эта функция должна вызываться статически.

PEAR_ErrorStack::setDefaultLogger()

PEAR_ErrorStack::setDefaultLogger()  --  Set up a PEAR::Log object for all error stacks that don't have one

Описание

Set up a PEAR::Log object for all error stacks that don't have one

Параметр

Log &$log

Throws

No exceptions thrown.

Заметка

Эта функция должна вызываться статически.

PEAR_ErrorStack::setErrorMessageTemplate()

PEAR_ErrorStack::setErrorMessageTemplate()  -- Set the Error Message Template array

Описание

The array format must be: array(error code => 'message template',...)

Error message parameters passed into push() will be used as input for the error message. If the template is 'message %foo% was %bar%', and the parameters are array('foo' => 'one', 'bar' => 'six'), the error message returned will be 'message one was six'

Параметр

mixed $template

Throws

No exceptions thrown.

Заметка

Эта функция не должна вызываться статически.

PEAR_ErrorStack::setLogger()

PEAR_ErrorStack::setLogger()  --  Set up a PEAR::Log object for this error stack

Описание

Set a PEAR::Log object to use for a specific error stack instance

Параметр

Log &$log

Throws

No exceptions thrown.

Заметка

Эта функция не должна вызываться статически.

PEAR_ErrorStack::setMessageCallback()

PEAR_ErrorStack::setMessageCallback()  --  Set an error code => error message mapping callback

Описание

This method sets the callback that can be used to generate error messages for any PEAR_ErrorStack instance

Параметр

mixed $msgCallback

Throws

No exceptions thrown.

Заметка

Эта функция не должна вызываться статически.

PEAR_ErrorStack::singleton()

PEAR_ErrorStack::singleton() -- Return a single error stack for this package.

Synopsis

require_once 'PEAR/ErrorStack.php';

PEAR_ErrorStack & PEAR_ErrorStack::singleton (string $package [, callback $msgCallback = FALSE [, callback $contextCallback = FALSE [, boolean $throwPEAR_Error = FALSE, string [$stackClass = 'PEAR_ErrorStack']]]])

Backwards Compatibility Warning

Внимание

As of PEAR 1.3.2, PEAR_ErrorStack no longer instantiates and returns an Exception object in PHP5, and the second-to-last parameter has been removed. Code that relies upon this behavior will break.

Описание

Note that all parameters are ignored if the stack for package $package has already been instantiated

Параметр

string $package

name of the package this error stack represents

callback $msgCallback

callback used for error message generation

callback $contextCallback

callback used for context generation, defaults to getFileLine()

boolean $throwPEAR_Error

If TRUE, then PEAR::raiseError() will be called and a PEAR_Error object will be returned from calls to PEAR_ErrorStack::push()

string $stackClass

class to instantiate

Throws

No exceptions thrown.

Заметка

Эта функция должна вызываться статически.

PEAR_ErrorStack::staticGetErrors()

PEAR_ErrorStack::staticGetErrors() --  Get a list of all errors since last purge, organized by package

Backwards Compatibility Warning

Внимание

As of PEAR 1.3.2, the second parameter is a new parameter $level. Any code that relies on $merge being the second parameter will break.

Описание

Static version of PEAR_ErrorStack::getErrors() , returns all errors from all singleton stacks.

Параметр

boolean $purge

Set to purge the error stack of existing errors

string $level

Level name to check for a particular severity. Use this to determine whether only a particular class of errors has occurred, such as whether any warnings have occurred (errors will be ignored)

boolean $merge

Set to return a flat array, not organized by package

array $sortfunc

Function used to sort a merged array - default sorts by time, and should be good for most cases

Throws

No exceptions thrown.

Заметка

Эта функция должна вызываться статически.

PEAR_ErrorStack::staticHasErrors()

PEAR_ErrorStack::staticHasErrors()  --  Determine whether there are any errors on any error stack

Описание

Static version of PEAR_ErrorStack::hasErrors(). Returns TRUE if any singleton stack has any errors pending. Since PEAR 1.3.2, If $package is specified, it will call PEAR_ErrorStack::hasErrors for the singleton error stack of that package. If level is specified, hasErrors will ignore any errors not conforming to the error level specified. Use this to simulate error_reporting(E_NOTICE), for example

Параметр

string|FALSE $package

Package name to retrieve error information from, or false to retrieve error information from all singleton stacks

string $level

Level name to check for a particular severity. Use this to determine whether only a particular class of errors has occurred, such as whether any warnings have occurred (errors will be ignored)

Throws

No exceptions thrown.

Заметка

Эта функция должна вызываться статически.

PEAR_ErrorStack::staticPop()

PEAR_ErrorStack::staticPop()  --  Static version of pop()

Описание

Pop an error off of the error stack, static method

Параметр

string $package

Package name to retrieve error message from

Возвращаемое значение

returns if compatibility mode is on, a PEAR_Error is also thrown.

Заметка

since PEAR 1.5.0a1

Throws

No exceptions thrown.

Заметка

Эта функция должна вызываться статически.

PEAR_ErrorStack::staticPopCallback()

PEAR_ErrorStack::staticPopCallback() -- Remove a callback from every error callback stack

Описание

Pop a callback from every Error Stack. No check is made to determine whether this is a good idea, so use with discretion.

Throws

No exceptions thrown.

Заметка

Эта функция должна вызываться статически.

PEAR_ErrorStack::staticPush()

PEAR_ErrorStack::staticPush()  --  Static version of push()

Описание

Параметр

string $package

Package name this error belongs to

integer $code

Package-specific error code

string $level

Error level. This is NOT spell-checked

array $params

associative array of error parameters

string $msg

Error message, or a portion of it if the message is to be generated

array $repackage

If this error re-packages an error pushed by another package, place the array returned from pop() in this parameter

array $backtrace

Protected parameter: use this to pass in the debug_backtrace that should be used to find error context

Возвращаемое значение

returns if compatibility mode is on, a PEAR_Error is also thrown.

Throws

No exceptions thrown.

Заметка

Эта функция должна вызываться статически.

PEAR_ErrorStack::staticPushCallback()

PEAR_ErrorStack::staticPushCallback()  --  Set an error Callback for every package's error stack

Описание

Set an error callback for every package's singleton error stack.

Параметр

string|array $cb

Throws

No exceptions thrown.

Заметка

Эта функция должна вызываться статически.

PEAR_ErrorStack::_log()

PEAR_ErrorStack::_log() -- Log an error using PEAR::Log

Описание

This is a protected function, and should only be called by child classes that extend PEAR_ErrorStack

Параметр

array $err

Error array

array $levels

Error level => Log constant map

Throws

throws no exceptions thrown

Заметка

Эта функция не должна вызываться статически.

Package PEAR_ErrorStack Constants

Package PEAR_ErrorStack Constants -- Constants defined in and used by PEAR_ErrorStack

System

Содержание
Введение -- Общая информация
System::rm -- удаляет файлы
System::mkDir -- создает директории
System::&cat -- объединение и вывод содержимого файлов
System::mktemp -- создает временные файлы и директории
System::tmpdir -- получает путь к директории для временных файлов
System::which -- показывает полный путь к системной утилите

Функции для работы с комадной строкой

System предоставляет API для написания кроссплатформенных программ, работающих с командной строкой.

Введение

Введение -- Общая информация

Командная строка

Функции класса System называются так же, как и утилиты командной строки
if (!System::rm('-r file1 dir1')) {
	print "Could not delete all the files";
}
Аргументы функциям могут передаваться в виде строки или массива:
System::rm(array('-r', 'file1', 'dir1'));
Методы System работают так же, как обычные функции PHP и возвращают FALSE, если операция не может быть выполнена. При этом выполнение операции не остановится в случае ошибки, а будет продолжаться. Например, если вы пытаетесь удалить три файла и первый не может быть удален, то следующие два будут удалены, но функция вернет FALSE.

Ошибки будут выведены с помощью функции trigger_error()(), для их отключения следует использовать префикс '@' (например: @System::mkdir('-p dir1/dir2/dir3');).

Совместимость

Класс System предоставляет интерфейс к функциям файловой системы. Они носят те же имена, что и утилиты для работы с файловой системой в Unix и поддерживают те же опции независимо от вашей операционной системы.

На данный момент функции были протестированы под Linux и Windows. Сообщения о поддержке других систем приветствуются.

Внимание

На ранних версиях PHP 4 unlink() может завершаться с ошибкой на Windows. Эта ошибка уже исправлена в новых версиях.

Документация

Это справочное руководство описывает параметры функций класса System, обычно представляющие из себя строки. Аргументы и опции конкретных команд не описываются здесь. Подробности ищите в мануале по конкретной команде на системах *nix:
man имякоманды
Если мануал на вашей системе недоступен - посетите сборник мануалов по командам Unix онлайн

System::rm

System::rm -- удаляет файлы

Описание

Команда rm удаляет файлы. Поддерживается удаление нескольких файлов и рекурсивное удаление директорий.

Параметр

  • string $args - аргументы для rm

Возвращаемое значение

mixed - TRUE при успешном завершении

Заметка

Эта функция может быть вызвана статически.

System::mkDir

System::mkDir -- создает директории

Описание

Создает директории.

Параметр

  • string $args - имя директории/директорий, которые надо создать

Возвращаемое значение

bool - TRUE в случае успеха

Заметка

Эта функция может быть вызвана статически.

System::&cat

System::&cat -- объединение и вывод содержимого файлов

Описание

Объединяет и выводит файлы. Использует fopen(), должна работать и с удаленными файлами.

Параметр

  • string $args - аргументы

Возвращаемое значение

boolean - TRUE при нормальном завершении

Заметка

Эта функция может быть вызвана статически.

System::mktemp

System::mktemp -- создает временные файлы и директории

Описание

Создает временные файлы и директории. Эта функция удалит все созданные ей файлы во время завершения работы скрипта.

Параметр

  • string $args - Аргументы

    • prefix - строка, которой будут префиксированы имена временных файлов (по умолчанию - tmp).

    • -d - будет создана директория, а не файл.

    • -t - директория, в которой будет создан временный файл или директория. Если этот параметр не указан, то используется переменная окружения TMP на Windows или TMPDIR на Unix. Если эти переменные тоже отсутствуют, то используются c:\windows\temp или /tmp соответственно.

Возвращаемое значение

mixed - полный путь к создаваемому файлу или директории; или FALSE в случае неудачи.

Заметка

Эта функция может быть вызвана статически.

System::tmpdir

System::tmpdir -- получает путь к директории для временных файлов

Описание

Получает из переменных окружения путь к директории для временных файлов, установленный в системе.

Возвращаемое значение

string - директория для временных файлов в системе

Заметка

Эта функция может быть вызвана статически.

В php.ini-recommended убран по умолчанию параметр E из директивы variables_order, что делает недоступным массив $_ENV.

System::which

System::which -- показывает полный путь к системной утилите

Описание

Показывает полный путь к системной утилите.

Параметр

  • string $program - искомая утилита

  • boolean $fallback - значение, которое возвращается в случае, если утилита не была найдена

Возвращаемое значение

mixed - строка, содержащая полный путь или FALSE в случае неудачи

Заметка

Эта функция может быть вызвана статически.


Глава 28. Классы PPM

Классы PPM предоставляют интерфейс для администрирования и управления пакетами PEAR.


PEAR_Autoload

Содержание
PEAR_Autoloader::addAggregateObject() -- Add an aggregate object to object.
PEAR_Autoloader::addAutoload() -- Add one or more autoload entries
PEAR_Autoloader::removeAggregateObject() -- Remove an aggregate object
PEAR_Autoloader::removeAutoload() -- Remove an autoload entry
PEAR_Autoloader::__call() -- Overloaded object call handler

Этот класс предназначен для объектов, из которых вы хотите вынести часть кода в отдельные классы. Это может быть полезно в том случае, если у вас есть класс, который не очень часто используется и вы бы не хотели, чтобы он парсился при каждом запросе.

Дерево классов для PEAR_Autoloader

  • PEAR

    • PEAR_Autoloader

PEAR_Autoloader::addAggregateObject()

PEAR_Autoloader::addAggregateObject() -- Add an aggregate object to object.

Описание

Add an aggregate object to this object. If the specified class is not defined, loading it will be attempted following PEAR's file naming scheme. All the methods in the class will be aggregated, except private ones (name starting with an underscore) and constructors.

Параметр

string $classname

what class to instantiate for the object.

Заметка

Эта функция не должна вызываться статически.

PEAR_Autoloader::addAutoload()

PEAR_Autoloader::addAutoload() -- Add one or more autoload entries

Описание

Add one or more autoload entries.

Параметр

string $method

which method to autoload

string $classname

which class to find the method in. If the $method parameter is an array, this parameter may be omitted (and will be ignored if not), and the $method parameter will be treated as an associative array with method names as keys and class names as values.

Заметка

Эта функция не должна вызываться статически.

PEAR_Autoloader::removeAggregateObject()

PEAR_Autoloader::removeAggregateObject() -- Remove an aggregate object

Описание

Remove an aggregate object.

Параметр

string $classname

the class of the object to remove

Возвращаемое значение

bool Возвращает TRUE в случае успеха и FALSE при неудаче.

Заметка

Эта функция не должна вызываться статически.

PEAR_Autoloader::removeAutoload()

PEAR_Autoloader::removeAutoload() -- Remove an autoload entry

Описание

Remove an autoload entry.

Параметр

string $method

which method to remove the autoload entry for

Возвращаемое значение

bool Возвращает TRUE в случае успеха и FALSE при неудаче.

Заметка

Эта функция не должна вызываться статически.

PEAR_Autoloader::__call()

PEAR_Autoloader::__call() -- Overloaded object call handler

Описание

Overloaded object call handler, called each time an undefined/aggregated method is invoked. This method repeats the call in the right aggregate object and passes on the return value.

Параметр

string $method

which method that was called

string $args

An array of the parameters passed in the original call

mixed &$retval

Возвращаемое значение

mixed - The return value from the aggregated method, or a PEAR_Error if the called method was unknown.

Заметка

Эта функция не должна вызываться статически.


PEAR_Builder

Содержание
PEAR_Builder::PEAR_Builder() -- constructor
PEAR_Builder::build() -- Build an extension from source
PEAR_Builder::log() -- 
PEAR_Builder::phpizeCallback() -- Message callback function when running phpize

Класс для создания (компиляции) модулей

Дерево классов для PEAR_Builder

  • PEAR_Common

    • PEAR_Builder

PEAR_Builder::PEAR_Builder()

PEAR_Builder::PEAR_Builder() -- constructor

Описание

PEAR_Builder constructor

Параметр

object &$ui

user interface object (instance of PEAR_Frontend_*)

Заметка

Эта функция может быть вызвана статически.

PEAR_Builder::build()

PEAR_Builder::build() -- Build an extension from source

Описание

Build an extension from source. Runs phpize in the source directory, but compiles in a temporary directory (/var/tmp/pear-build-USER/PACKAGE-VERSION).

Параметр

string $descfile

path to XML package description file

mixed $callback

callback function used to report output

Возвращаемое значение

array - an array of associative arrays with built files, format:
array( array( 'file' => '/path/to/ext.so',
                    'php_api' => YYYYMMDD,
                    'zend_mod_api' => YYYYMMDD,
                    'zend_ext_api' =>; YYYYMMDD ),
       ... )

См. также

PEAR_Common::infoFromDescriptionFile

Заметка

Эта функция не должна вызываться статически.

PEAR_Builder::log()

PEAR_Builder::log() -- 

Описание

Этот пакет пока не документирован.

Параметр

mixed $level

mixed $msg

Заметка

Эта функция не должна вызываться статически.

PEAR_Builder::phpizeCallback()

PEAR_Builder::phpizeCallback() -- Message callback function when running phpize

Описание

Message callback function used when running the phpize program. Extracts the API numbers used. Ignores other message types than "cmdoutput".

Параметр

string $what

the type of message

mixed $data

the message

Заметка

Эта функция не должна вызываться статически.


PEAR_Command

Содержание
PEAR_Command::factory() -- get object for executing a command.
PEAR_Command::getCommands() -- get list of currently supported commands
PEAR_Command::getDescription() -- get description for a command
PEAR_Command::getGetoptArgs() -- compiles arguments for getopt
PEAR_Command::getHelp() -- get help for command
PEAR_Command::getShortcuts() -- get list of command shortcuts.
PEAR_Command::registerCommands() -- scan the command directory

Командный класс PEAR, простейшая фабрика для административных команд

PEAR_Command::factory()

PEAR_Command::factory() -- get object for executing a command.

Описание

Get the right object for executing a command.

Параметр

string $command

The name of the command

object &$config

Instance of PEAR_Config object

Возвращаемое значение

object the command object

Заметка

Эта функция должна вызываться статически.

PEAR_Command::getCommands()

PEAR_Command::getCommands() -- get list of currently supported commands

Описание

Get the list of currently supported commands, and what classes implement them.

Возвращаемое значение

array command => implementing class

Заметка

Эта функция должна вызываться статически.

PEAR_Command::getDescription()

PEAR_Command::getDescription() -- get description for a command

Описание

Get description for a command.

Параметр

string $command

Name of the command

Возвращаемое значение

string command description

Заметка

Эта функция должна вызываться статически.

PEAR_Command::getGetoptArgs()

PEAR_Command::getGetoptArgs() -- compiles arguments for getopt

Описание

Compiles arguments for getopt.

Параметр

string $command

command to get optstring for

string &$short_args

(reference) short getopt format

array &$long_args

(reference) long getopt format

Заметка

Эта функция должна вызываться статически.

PEAR_Command::getHelp()

PEAR_Command::getHelp() -- get help for command

Описание

Get help for command.

Параметр

string $command

Name of the command to return help for

Возвращаемое значение

string help text

Заметка

Эта функция должна вызываться статически.

PEAR_Command::getShortcuts()

PEAR_Command::getShortcuts() -- get list of command shortcuts.

Описание

Get the list of command shortcuts.

Возвращаемое значение

array shortcut => command

Заметка

Эта функция должна вызываться статически.

PEAR_Command::registerCommands()

PEAR_Command::registerCommands() -- scan the command directory

Описание

Scan through the Command directory looking for classes and see what commands they implement.

Параметр

boolean $merge

if FALSE (default), the new list of commands should replace the current one. If TRUE, new entries will be merged with old.

string $dir

where (what directory) to look for classes, defaults to the Command subdirectory of the directory from where this file (__FILE__) is included.

Возвращаемое значение

bool TRUE on success

Заметка

Эта функция должна вызываться статически.


PEAR_Common

Содержание
PEAR_Common::PEAR_Common() -- PEAR_Common constructor
PEAR_Common::addTempFile() -- register a temporary file or directory
PEAR_Common::analyzeSourceCode() -- analyze the source code of the given PHP file
PEAR_Common::buildProvidesArray() -- Build a array
PEAR_Common::downloadHttp() -- Download a file through HTTP
PEAR_Common::infoFromAny() -- Returns package information from different sources
PEAR_Common::infoFromDescriptionFile() -- Returns information about a package file
PEAR_Common::infoFromString() -- Returns information about a package file
PEAR_Common::infoFromTgzFile() -- Returns information about a package file
PEAR_Common::log() -- Logging method
PEAR_Common::mkDirHier() -- Create a directory and necessary parent directories
PEAR_Common::mkTempDir() -- Create and register a temporary directory.
PEAR_Common::setFrontendObject() -- Set object representing frontend to use.
PEAR_Common::validatePackageInfo() -- Validate XML package definition file
PEAR_Common::validPackageName() -- Test whether a string is a valid package name
PEAR_Common::xmlFromInfo() -- Return an XML document based on the package info

Класс, предоставляющий основную функциональность для административных классов PEAR

Дерево классов для PEAR_Common()

  • PEAR

    • PEAR_Common

PEAR_Common::PEAR_Common()

PEAR_Common::PEAR_Common() -- PEAR_Common constructor

Описание

PEAR_Common constructor

Заметка

Эта функция может быть вызвана статически.

PEAR_Common::addTempFile()

PEAR_Common::addTempFile() -- register a temporary file or directory

Описание

Register a temporary file or directory. When the destructor is executed, all registered temporary files and directories are removed.

Параметр

string $file

name of file or directory

Заметка

Эта функция может быть вызвана статически.

PEAR_Common::analyzeSourceCode()

PEAR_Common::analyzeSourceCode() -- analyze the source code of the given PHP file

Описание

Analyze the source code of the given PHP file

Параметр

string $file

Filename of the PHP file

Возвращаемое значение

array - hash list of declared_classes, declared_methods, declared_functions and used_classes

Заметка

Эта функция может быть вызвана статически.

PEAR_Common::buildProvidesArray()

PEAR_Common::buildProvidesArray() -- Build a array

Описание

Build a "provides" array from data returned by analyzeSourceCode(). The format of the built array is like this:
array(
        'class;MyClass' => 
           array(
           'type' => 'class',
           'name' => 'MyClass'
           ),
           ...  
        )

Параметр

array $srcinfo

array with information about a source file as returned by the analyzeSourceCode() method.

Заметка

Эта функция не должна вызываться статически.

PEAR_Common::downloadHttp()

PEAR_Common::downloadHttp() -- Download a file through HTTP

Описание

Download a file through HTTP. Considers suggested file name in Content-disposition: header and can run a callback function for different events. The callback will be called with two parameters: the callback type, and parameters. The implemented callback types are:

  • 'setup' - called at the very beginning, parameter is a UI object that should be used for all output

  • 'message' - the parameter is a string with an informational message

  • 'saveas' - may be used to save with a different file name, the parameter is the filename that is about to be used. If a 'saveas' callback returns a non-empty string, that file name will be used as the filename instead. Note that $save_dir will not be affected by this, only the basename of the file.

  • 'start' - download is starting, parameter is number of bytes that are expected, or -1 if unknown

  • 'bytesread' - parameter is the number of bytes read so far

  • 'done' - download is complete, parameter is the total number of bytes read

  • 'connfailed' - if the TCP connection fails, this callback is called with
    array(host,port,errno,errmsg)

  • 'writefailed' - if writing to disk fails, this callback is called with
    array(destfile,errmsg)

If an HTTP proxy has been configured (http_proxy PEAR_Config setting), the proxy will be used.

Параметр

string $url

the URL to download

object &$ui

PEAR_Frontend_* instance

string $save_dir

directory to save file in

mixed $callback

function/method to call for status updates

object $config

PEAR_Config instance

Возвращаемое значение

string - Returns the full path of the downloaded file or a PEAR error on failure. If the error is caused by socket-related errors, the error object will have the fsockopen error code available through getCode().

Заметка

Эта функция не должна вызываться статически.

PEAR_Common::infoFromAny()

PEAR_Common::infoFromAny() -- Returns package information from different sources

Описание

Returns package information from different sources. This method is able to extract information about a package from a .tgz archive or from a XML package definition file.

Параметр

string $info

Filename of the source ('package.xml', '<package>.tgz')

Возвращаемое значение

string - Package information

Заметка

Эта функция не должна вызываться статически.

PEAR_Common::infoFromDescriptionFile()

PEAR_Common::infoFromDescriptionFile() -- Returns information about a package file

Описание

Returns information about a package file. Expects the name of a package xml file as input.

Параметр

string $descfile

name of package xml file

Возвращаемое значение

array - array with package information

Заметка

Эта функция не должна вызываться статически.

PEAR_Common::infoFromString()

PEAR_Common::infoFromString() -- Returns information about a package file

Описание

Returns information about a package file. Expects the contents of a package xml file as input.

Параметр

string $data

content of package xml file

Возвращаемое значение

array - array with package information

Заметка

Эта функция не должна вызываться статически.

PEAR_Common::infoFromTgzFile()

PEAR_Common::infoFromTgzFile() -- Returns information about a package file

Описание

Returns information about a package file. Expects the name of a gzipped tar file as input.

Параметр

string $file

name of .tgz file

Возвращаемое значение

array - array with package information

Заметка

Эта функция не должна вызываться статически.

PEAR_Common::log()

PEAR_Common::log() -- Logging method

Описание

Logging method.

Параметр

integer $level

log level (0 is quiet, higher is noisier)

string $msg

message to write to the log

Заметка

Эта функция не должна вызываться статически.

PEAR_Common::mkDirHier()

PEAR_Common::mkDirHier() -- Create a directory and necessary parent directories

Описание

Wrapper to System::mkDir(), creates a directory as well as any necessary parent directories.

Параметр

string $dir

directory name

Возвращаемое значение

bool - Возвращает TRUE при удаче и PEAR_Error в обратном случае.

Заметка

Эта функция не должна вызываться статически.

PEAR_Common::mkTempDir()

PEAR_Common::mkTempDir() -- Create and register a temporary directory.

Описание

Create and register a temporary directory.

Параметр

string $tmpdir

Directory to use as tmpdir. Will use system defaults (for example /tmp or c:\windows\temp) if not specified.

Возвращаемое значение

string name of created directory

Заметка

Эта функция не должна вызываться статически.

PEAR_Common::setFrontendObject()

PEAR_Common::setFrontendObject() -- Set object representing frontend to use.

Описание

Set object that represents the frontend to be used.

Параметр

object $ui

Reference of the frontend object

Заметка

Эта функция не должна вызываться статически.

PEAR_Common::validatePackageInfo()

PEAR_Common::validatePackageInfo() -- Validate XML package definition file

Описание

Validate XML package definition file.

Параметр

string $info

Filename of the package archive or of the package definition file

array $errors

Array that will contain the errors

array $warnings

Array that will contain the warnings

string $dir_prefix

directory where source files may be found, or empty if they are not available

Возвращаемое значение

bool - TRUE if valid

Заметка

Эта функция не должна вызываться статически.

PEAR_Common::validPackageName()

PEAR_Common::validPackageName() -- Test whether a string is a valid package name

Описание

Test whether a string contains a valid package name.

Параметр

string $name

the package name to test

Возвращаемое значение

bool - Возвращает TRUE в случае успеха и FALSE при неудаче.

Заметка

Эта функция не должна вызываться статически.

PEAR_Common::xmlFromInfo()

PEAR_Common::xmlFromInfo() -- Return an XML document based on the package info

Описание

Return an XML document based on the package info (as returned by the PEAR_Common::infoFrom*() methods).

Параметр

array $pkginfo

package info

Возвращаемое значение

string - XML data

Заметка

Эта функция не должна вызываться статически.


PEAR_Config

Содержание
PEAR_Config::PEAR_Config() -- Constructor
PEAR_Config::definedBy() -- Tells what config layer that gets to define a key
PEAR_Config::get() -- Returns a configuration value
PEAR_Config::getDocs() -- Get the documentation for a config value
PEAR_Config::getGroup() -- Get the parameter group for a config key
PEAR_Config::getGroupKeys() -- Get the list of the parameters in a group
PEAR_Config::getGroups() -- Get the list of parameter groups
PEAR_Config::getKeys() -- Get all the current config keys
PEAR_Config::getLayers() -- Returns the layers defined
PEAR_Config::getPrompt() -- Get short documentation for a config value
PEAR_Config::getSetValues() -- Get the list of allowed set values for a config value
PEAR_Config::getType() -- Get the type of a config value
PEAR_Config::isDefined() -- Tells whether a key exists as config value
PEAR_Config::isDefinedLayer() -- Tells whether a config layer exists
PEAR_Config::mergeConfigFile() -- Merges data into a config layer from a file
PEAR_Config::readConfigFile() -- Reads configuration data from a file
PEAR_Config::remove() -- Remove a config key from a config layer
PEAR_Config::removeLayer() -- Temporarily remove an entire config layer
PEAR_Config::set() -- Set config value in specific layer
PEAR_Config::singleton() -- Return a reference of a PEAR_Config object
PEAR_Config::store() -- Stores configuration data in a layer
PEAR_Config::toDefault() -- Revert value of config key to the system-defined one
PEAR_Config::writeConfigFile() -- Write data into config layer from file

Дерево классов для PEAR_Config()

  • PEAR

    • PEAR_Config

PEAR_Config::PEAR_Config()

PEAR_Config::PEAR_Config() -- Constructor

Описание

Constructor

Параметр

string $user_file

file to read user-defined options from

string $system_file

file to read system-wide defaults from

Заметка

Эта функция не должна вызываться статически.

PEAR_Config::definedBy()

PEAR_Config::definedBy() -- Tells what config layer that gets to define a key

Описание

Tells what config layer that gets to define a key.

Параметр

string $key

config key

Возвращаемое значение

string - the config layer, or an empty string if not found

Заметка

Эта функция не должна вызываться статически.

PEAR_Config::get()

PEAR_Config::get() -- Returns a configuration value

Описание

Returns a configuration value, prioritizing layers as per the layers property.

Параметр

string $key

config key

mixed $layer

layer key

Возвращаемое значение

mixed the config value, or NULL if not found

Заметка

Эта функция не должна вызываться статически.

PEAR_Config::getDocs()

PEAR_Config::getDocs() -- Get the documentation for a config value

Описание

Get the documentation for a config value.

Параметр

string $key

config key

Возвращаемое значение

string - documentation string

Заметка

Эта функция не должна вызываться статически.

PEAR_Config::getGroup()

PEAR_Config::getGroup() -- Get the parameter group for a config key

Описание

Get the parameter group for a config key.

Параметр

string $key

config key

Возвращаемое значение

string - parameter group

Заметка

Эта функция не должна вызываться статически.

PEAR_Config::getGroupKeys()

PEAR_Config::getGroupKeys() -- Get the list of the parameters in a group

Описание

Get the list of the parameters in a group.

Параметр

string $group

parameter group

Возвращаемое значение

array list of parameters in $group

Заметка

Эта функция не должна вызываться статически.

PEAR_Config::getGroups()

PEAR_Config::getGroups() -- Get the list of parameter groups

Описание

Get the list of parameter groups.

Возвращаемое значение

array - list of parameter groups

Заметка

Эта функция не должна вызываться статически.

PEAR_Config::getKeys()

PEAR_Config::getKeys() -- Get all the current config keys

Описание

Get all the current config keys

Возвращаемое значение

array - simple array of config keys

Заметка

Эта функция не должна вызываться статически.

PEAR_Config::getLayers()

PEAR_Config::getLayers() -- Returns the layers defined

Описание

Returns the layers defined, except the 'default' one

Возвращаемое значение

array the defined layers

Заметка

Эта функция не должна вызываться статически.

PEAR_Config::getPrompt()

PEAR_Config::getPrompt() -- Get short documentation for a config value

Описание

Get the short documentation for a config value.

Параметр

string $key

config key

Возвращаемое значение

string short documentation string

Заметка

Эта функция не должна вызываться статически.

PEAR_Config::getSetValues()

PEAR_Config::getSetValues() -- Get the list of allowed set values for a config value

Описание

Get the list of allowed set values for a config value. Returns NULL for config values that are not sets.

Параметр

string $key

config key

Возвращаемое значение

array - enumerated array of set values, or NULL if the config key is unknown or not a set

Заметка

Эта функция не должна вызываться статически.

PEAR_Config::getType()

PEAR_Config::getType() -- Get the type of a config value

Описание

Get the type of a config value.

Параметр

string $key

config key

Возвращаемое значение

string - type, one of "string", "integer", "file", "directory", "set" or "password".

Заметка

Эта функция не должна вызываться статически.

PEAR_Config::isDefined()

PEAR_Config::isDefined() -- Tells whether a key exists as config value

Описание

Tells whether a given key exists as a config value.

Параметр

string $key

config key

Возвращаемое значение

bool - whether $key exists in this object

Заметка

Эта функция не должна вызываться статически.

PEAR_Config::isDefinedLayer()

PEAR_Config::isDefinedLayer() -- Tells whether a config layer exists

Описание

Tells whether a given config layer exists.

Параметр

string $layer

config layer

Возвращаемое значение

bool - whether $layer exists in this object

Заметка

Эта функция не должна вызываться статически.

PEAR_Config::mergeConfigFile()

PEAR_Config::mergeConfigFile() -- Merges data into a config layer from a file

Описание

Merges data into a config layer from a file. Does the same thing as readConfigFile(), except it does not replace all existing values in the config layer.

Параметр

string $file

file to read from

boolean $override

whether to overwrite existing data

string $layer

config layer to insert data into ('user' or 'system')

Возвращаемое значение

bool - Возвращает TRUE при удаче и PEAR_Error в обратном случае.

Заметка

Эта функция не должна вызываться статически.

PEAR_Config::readConfigFile()

PEAR_Config::readConfigFile() -- Reads configuration data from a file

Описание

Reads configuration data from a file. All existing values in the config layer are discarded and replaced with data from the file.

Параметр

string $file

file to read from, if NULL or not specified, the last-used file for the same layer (second param) is used

string $layer

config layer to insert data into ('user' or 'system')

Возвращаемое значение

bool - Возвращает TRUE при удаче и PEAR_Error в обратном случае.

Заметка

Эта функция не должна вызываться статически.

PEAR_Config::remove()

PEAR_Config::remove() -- Remove a config key from a config layer

Описание

Remove a config key from a specific config layer.

Параметр

string $key

config key

string $layer

config layer

Возвращаемое значение

bool - Возвращает TRUE при удаче и PEAR_Error в обратном случае.

Заметка

Эта функция не должна вызываться статически.

PEAR_Config::removeLayer()

PEAR_Config::removeLayer() -- Temporarily remove an entire config layer

Описание

Temporarily remove an entire config layer. USE WITH CARE!

Параметр

string $layer

config key

Возвращаемое значение

bool - Возвращает TRUE в случае успеха и FALSE при неудаче.

Заметка

Эта функция не должна вызываться статически.

PEAR_Config::set()

PEAR_Config::set() -- Set config value in specific layer

Описание

Set a config value in a specific layer (defaults to 'user'). Enforces the types defined in the configuration_info array. An integer config variable will be cast to int, and a set config variable will be validated against its legal values.

Параметр

string $key

config key

string $value

config value

string $layer

config layer

Возвращаемое значение

bool - Возвращает TRUE в случае успеха и FALSE при неудаче.

Заметка

Эта функция не должна вызываться статически.

PEAR_Config::singleton()

PEAR_Config::singleton() -- Return a reference of a PEAR_Config object

Описание

If you want to keep only one instance of this class in use, this method will give you a reference to the last created PEAR_Config object if one exists, or create a new object.

Параметр

string $user_file

file to read user-defined options from

string $system_file

file to read system-wide defaults from

Возвращаемое значение

object - an existing or new PEAR_Config instance

Заметка

Эта функция должна вызываться статически.

PEAR_Config::store()

PEAR_Config::store() -- Stores configuration data in a layer

Описание

Stores configuration data in a layer.

Параметр

string $layer

config layer to store

Возвращаемое значение

bool - Возвращает TRUE при удаче и PEAR_Error в обратном случае.

Заметка

Эта функция не должна вызываться статически.

PEAR_Config::toDefault()

PEAR_Config::toDefault() -- Revert value of config key to the system-defined one

Описание

Unset the user-defined value of a config key, reverting the value to the system-defined one.

Параметр

string $key

config key

Возвращаемое значение

bool - Возвращает TRUE в случае успеха и FALSE при неудаче.

Заметка

Эта функция не должна вызываться статически.

PEAR_Config::writeConfigFile()

PEAR_Config::writeConfigFile() -- Write data into config layer from file

Описание

Writes data into a config layer from a file.

Параметр

string $file

file to read from

boolean $layer

whether to overwrite existing data

Возвращаемое значение

bool - Возвращает TRUE при удаче и PEAR_Error в обратном случае.

Заметка

Эта функция не должна вызываться статически.


PEAR_Dependency

Содержание
PEAR_Dependency::PEAR_Dependency() -- constructor
PEAR_Dependency::callCheckMethod() -- Maps the xml dependency definition
PEAR_Dependency::checkExtension() -- Check Extension dependency
PEAR_Dependency::checkOS() -- Check Operating system dependency
PEAR_Dependency::checkPackage() -- check Package dependency
PEAR_Dependency::checkPHP() -- Check PHP version
PEAR_Dependency::checkProgram() -- Check external program
PEAR_Dependency::checkSAPI() -- Check SAPI backend
PEAR_Dependency::checkZend() -- Check Zend version

Контролирует зависимости между классами

PEAR_Dependency::PEAR_Dependency()

PEAR_Dependency::PEAR_Dependency() -- constructor

Описание

Constructor

Параметр

object &$registry

a PEAR_Registry instance

Заметка

Эта функция не должна вызываться статически.

PEAR_Dependency::callCheckMethod()

PEAR_Dependency::callCheckMethod() -- Maps the xml dependency definition

Описание

This method maps the xml dependency definition to the PEAR_Dependency one.

Параметр

mixed &$errmsg

this variable will contains an error message, if check fail

array $opts

An Array with all Dependency entries from the parsed XML package definition, ie:
$opts => Array
   (
       ['type'] => 'pkg',
       ['rel'] => 'ge',
       ['version'] => '3.4',
       ['name'] => 'HTML_Common'
    );

Возвращаемое значение

mixed - FALSE if all dependencies could be resolved successfully(!); or an PEAR_DEPENDENCY_* constant in case of unresolved dependencies.

Заметка

Эта функция не должна вызываться статически.

PEAR_Dependency::checkExtension()

PEAR_Dependency::checkExtension() -- Check Extension dependency

Описание

Extension dependencies check method

Параметр

mixed &$errmsg

this variable will contains an error message, if check fail

string $name

Name of the extension to test

string $req

Required extension version to compare with

string $relation

How to compare versions with eachother

Возвращаемое значение

mixed - FALSE if dependency could be resolved successfully(!); or an PEAR_DEPENDENCY_* constant in case of an unresolved dependency.

Заметка

Эта функция не должна вызываться статически.

PEAR_Dependency::checkOS()

PEAR_Dependency::checkOS() -- Check Operating system dependency

Описание

Operating system dependencies check method

Параметр

string &$errmsg

this variable will contains an error message, if check fail

string $os

Name of the operating system

Возвращаемое значение

mixed - FALSE if dependency could be resolved successfully(!); or an PEAR_DEPENDENCY_* constant in case of unresolved dependency.

Заметка

Эта функция не должна вызываться статически.

PEAR_Dependency::checkPackage()

PEAR_Dependency::checkPackage() -- check Package dependency

Описание

Package dependencies check method

Параметр

string &$errmsg

this variable will contains an error message, if check fail

string $name

Name of the package to test

string $req

Required package version to compare with

string $relation

How to compare versions with eachother

Возвращаемое значение

mixed - FALSE if dependency could be resolved successfully(!); or an PEAR_DEPENDENCY_* constant in case of unresolved dependency.

Заметка

Эта функция не должна вызываться статически.

PEAR_Dependency::checkPHP()

PEAR_Dependency::checkPHP() -- Check PHP version

Описание

PHP version check method

Параметр

mixed &$errmsg

this variable will contains an error message, if check fail

string $req

which version to compare

string $relation

how to compare the version

Возвращаемое значение

mixed - FALSE if dependency could be resolved successfully(!); or an PEAR_DEPENDENCY_* constant in case of unresolved dependency.

Заметка

Эта функция не должна вызываться статически.

PEAR_Dependency::checkProgram()

PEAR_Dependency::checkProgram() -- Check external program

Описание

External program check method. Looks for executable files in directories listed in the PATH environment variable.

Параметр

mixed &$errmsg

this variable will contains an error message, if check fail

string $program

which program to look for

Возвращаемое значение

mixed - FALSE if dependency could be resolved successfully(!); or an PEAR_DEPENDENCY_* constant in case of unresolved dependency.

Заметка

Эта функция не должна вызываться статически.

PEAR_Dependency::checkSAPI()

PEAR_Dependency::checkSAPI() -- Check SAPI backend

Описание

SAPI backend check method. Version comparison is not yet available here.

Параметр

mixed &$errmsg

this variable will contains an error message, if check fail

string $name

name of SAPI backend

string $req

which version to compare (currently unused)

string $relation

how to compare versions (currently hardcoded to 'has')

Возвращаемое значение

mixed - FALSE if dependency could be resolved successfully(!); or an PEAR_DEPENDENCY_* constant in case of unresolved dependency.

Заметка

Эта функция не должна вызываться статически.

PEAR_Dependency::checkZend()

PEAR_Dependency::checkZend() -- Check Zend version

Описание

Zend version check method

Параметр

mixed &$errmsg

this variable will contains an error message, if check fail

string $req

which version to compare

string $relation

how to compare the version

Возвращаемое значение

mixed - FALSE if dependency could be resolved successfully(!); or an PEAR_DEPENDENCY_* constant in case of unresolved dependency.

Заметка

Эта функция не должна вызываться статически.


PEAR_Installer

Административный класс, используемый для установки пакетов PEAR и поддержания базы установленных пакетов.

Дерево классов для PEAR_Installer()

  • PEAR_Common

    • PEAR_Installer

PEAR_Installer::PEAR_Installer()

PEAR_Installer::PEAR_Installer() -- constructor

Описание

PEAR_Installer constructor.

Параметр

object &$ui

user interface object (instance of PEAR_Frontend_*)

Заметка

Эта функция не должна вызываться статически.

PEAR_Installer::install()

PEAR_Installer::install() -- Installs package files

Описание

Installs the files within the package file specified.

Параметр

string $pkgfile

path to the package file

array $options

installating options, to enable an option use the option name as array key and TRUE or 1 as value.

  • $options['force'] = 1 - force installation

  • $options['register-only'] = 1 - update registry but don't install files

  • $options['upgrade'] = 1 - upgrade existing install

  • $options['soft'] = 1 - fail silently

Возвращаемое значение

array package info if successful

Заметка

Эта функция не должна вызываться статически.


PEAR_Packager

Административный класс, используемый для создания релизов пакетов PEAR.

Дерево классов для PEAR_Packager

  • PEAR_Common

    • PEAR_Packager

PEAR_Packager::PEAR_Packager()

PEAR_Packager::PEAR_Packager() -- constructor

Описание

constructor

Заметка

Эта функция может быть вызвана статически.

PEAR_Packager::package()

PEAR_Packager::package() -- Create Package archive

Описание

Creates a Package archive from package definition file and package files

Параметр

string $pkgfile

path to package definition file

boolean $compress

if TRUE package archive will be compessed using gzip

Возвращаемое значение

string - name of the created package archive

Заметка

Эта функция не должна вызываться статически.


PEAR_Registry

Содержание
PEAR_Registry::PEAR_Registry() -- constructor
PEAR_Registry::addPackage() -- Registers a package to the registry
PEAR_Registry::checkFileMap() -- Test whether a file belongs to a package
PEAR_Registry::deletePackage() -- Remove Package from registry
PEAR_Registry::listPackages() -- List all registered Packages
PEAR_Registry::packageExists() -- Check for Package
PEAR_Registry::packageInfo() -- Get Package information
PEAR_Registry::rebuildDepsFile() -- Rebuild dependencies file
PEAR_Registry::rebuildFileMap() -- Rebuild file map
PEAR_Registry::removePackageDep() -- Remove dependency information of a Package
PEAR_Registry::setPackageDep() -- Update or insert dependencies of a Package
PEAR_Registry::updatePackage() -- Update Package information

Административный класс, используемый для поддержания базы установленных пакетов.

Дерево классов для PEAR_Registry

  • PEAR

    • PEAR_Registry

PEAR_Registry::PEAR_Registry()

PEAR_Registry::PEAR_Registry() -- constructor

Описание

constructor

Параметр

string $pear_install_dir

PEAR install directory (for .php files)

Заметка

Эта функция не должна вызываться статически.

PEAR_Registry::addPackage()

PEAR_Registry::addPackage() -- Registers a package to the registry

Описание

Adds a Package entry to the registry

Параметр

string $package

Package name

array $info

additional information for the package entry

Возвращаемое значение

boolean - FALSE if Package is already registered;

Заметка

Эта функция не должна вызываться статически.

PEAR_Registry::checkFileMap()

PEAR_Registry::checkFileMap() -- Test whether a file belongs to a package

Описание

Test whether a file belongs to a package.

Параметр

string $path

file path, absolute or relative to the pear install dir

Возвращаемое значение

string - name of the package the file belongs to, or an empty string if the file does not belong to an installed package

Заметка

Эта функция не должна вызываться статически.

PEAR_Registry::deletePackage()

PEAR_Registry::deletePackage() -- Remove Package from registry

Описание

Removes a Package entry from the registry.

Параметр

string $package

Package name

Возвращаемое значение

boolean - Возвращает TRUE в случае успеха и FALSE при неудаче.

Заметка

Эта функция не должна вызываться статически.

PEAR_Registry::listPackages()

PEAR_Registry::listPackages() -- List all registered Packages

Описание

List all Packages registered in the registry.

Возвращаемое значение

array - list of package names

Заметка

Эта функция не должна вызываться статически.

PEAR_Registry::packageExists()

PEAR_Registry::packageExists() -- Check for Package

Описание

Checks wether a Package is registered in the registry or not.

Параметр

string $package

Package name

Возвращаемое значение

boolean - TRUE if package is registered

Заметка

Эта функция не должна вызываться статически.

PEAR_Registry::packageInfo()

PEAR_Registry::packageInfo() -- Get Package information

Описание

Returns (specific) information stored in the registry about a Package.

Параметр

string $package

Package name

string $key

the name of a specific information to get

Возвращаемое значение

mixed - an array with all information, or a key specific information, if $key was used; NULL if Package or specific information does not exist

Заметка

Эта функция не должна вызываться статически.

PEAR_Registry::rebuildDepsFile()

PEAR_Registry::rebuildDepsFile() -- Rebuild dependencies file

Описание

Rebuilds the dependencies file of the registry. Use this function if had trouble while installing Packages or a damaged registry.

Заметка

Эта функция не должна вызываться статически.

PEAR_Registry::rebuildFileMap()

PEAR_Registry::rebuildFileMap() -- Rebuild file map

Описание

Rebuilds the registry filemap. Use this function if had trouble while installing Packages or a damaged registry.

Заметка

Эта функция не должна вызываться статически.

PEAR_Registry::removePackageDep()

PEAR_Registry::removePackageDep() -- Remove dependency information of a Package

Описание

Removes the dependency information of a Package from the registry.

Параметр

string $package

Package name

Возвращаемое значение

mixed - TRUE if successful; or an array with a list of Packages depending on this Package

Заметка

Эта функция не должна вызываться статически.

PEAR_Registry::setPackageDep()

PEAR_Registry::setPackageDep() -- Update or insert dependencies of a Package

Описание

Update or insert a the dependencies of a package, prechecking that the package won't break any dependency in the process. (Dependencies of type 'pkg' only.

Параметр

string $package

Package name

string $new_version

Version of the Package

array $rel_deps

Package dependencies

Возвращаемое значение

mixed - TRUE if no dependencies found; or array with names of missing or outdated Packages

Заметка

Эта функция не должна вызываться статически.

PEAR_Registry::updatePackage()

PEAR_Registry::updatePackage() -- Update Package information

Описание

Updates the existing information of a Package in the registry.

Параметр

string $package

Package name

array $info

information to update

mixed $merge

if FALSE the old informations will be deleted completly an replaced with the new; if TRUE update only - unchanged values will remain.

Возвращаемое значение

boolean - Возвращает TRUE в случае успеха и FALSE при неудаче.

Заметка

Эта функция не должна вызываться статически.


PEAR_Remote

Содержание
PEAR_Remote::PEAR_Remote() -- constructor
PEAR_Remote::call() -- Execute a server function

Класс для осуществления удаленных операция с сервером пакетов PEAR.

Дерево классов для PEAR_Remote()

  • PEAR

    • PEAR_Remote

PEAR_Remote::PEAR_Remote()

PEAR_Remote::PEAR_Remote() -- constructor

Описание

constructor

Параметр

object &$config

an instance of PEAR_Config

Заметка

Эта функция не должна вызываться статически.

PEAR_Remote::call()

PEAR_Remote::call() -- Execute a server function

Описание

Sends a remote procedure call to a package server and returns the result.

Параметр

string $method

Name of the server method

mixed $args,...

server method specific parameters

Возвращаемое значение

mixed - result of the executed server method

Заметка

Эта функция не должна вызываться статически.

VI. PEAR Пакеты программ


Глава 29. Аутентификация

Предоставляет пакеты, позволяющие сделать свою систему аутентификации.


Auth

Содержание
Introduction -- A usage example
Storage drivers -- Introduction
Logging -- Introduction
Auth_Container_Array -- Authenticate against an array of usernames and passwords
Auth_Container_DB -- Authenticate against a database using DB
Auth_Container_DBLite -- Authenticate against a database using DB
Auth_Container_File -- Authenticate a password file using File_Passwd
Auth_Container_IMAP -- Authenticate against an IMAP server
Auth_Container_KADM5 -- Authenticate against a Kerberos 5 server
Auth_Container_LDAP -- Authenticate against an LDAP server
Auth_Container_MDB -- Authenticate against a database using MDB
Auth_Container_MDB2 -- Authenticate against a database using MDB2
Auth_Container_Multiple -- Authenticate against multiple Auth_Containers
Auth_Container_PEAR -- Authenticate against the PEAR website
Auth_Container_POP3 -- Authenticate against a POP3 server
Auth_Container_RADIUS -- Authenticate against a RADIUS server
Auth_Container_SAP -- Authenticate against a SAP server
Auth_Container_SMBPasswd -- Authenticate a SAMBA smbpasswd file using File_SMBPasswd
Auth_Container_SOAP -- Authenticate against a SOAP service
Auth_Container_SOAP5 -- Authenticate against a SOAP service
Auth_Container_vpopmail -- Authenticate against a vpopmail service
Custom Auth_Container -- Build a custom storage container
Auth_Frontend_HTML -- Default login form
Константы -- предопределенные константы
Auth::Auth() -- constructor
Auth::addUser() -- add a new user
Auth::attachLogObserver() -- Attach a log observer instance to the internal Log object
Auth::changePassword() -- change the password of a user
Auth::checkAuth() --  check if a session with valid authentication information exists
Auth::getAuth() -- check for an authenticated user
Auth::getAuthData() -- retrieve extra information stored within the auth session
Auth::getStatus() -- get the current status of the auth session
Auth::getUsername() -- get the username of the authenticated user
Auth::listUsers() -- list available users
Auth::logout() -- logout an authenticated user
Auth::removeUser() -- remove a user account
Auth::setAdvancedSecurity() -- Enables advanced security features. Turned off by default
Auth::setAllowLogin() -- Controls if the user will be allowed to login. Turned on by default
Auth::setAuth() -- set a specific user to be marked as logged in
Auth::setAuthData() -- store extra information with the Auth session
Auth::setCheckAuthCallback() -- set a callback to run when ever session validity is checked
Auth::setExpire() -- set expiration time for authentication
Auth::setFailedLoginCallback() -- set a callback for failed login attempts
Auth::setIdle() -- set maximum idle time for authentication
Auth::setLoginCallback() -- set a callback for successful login attempts
Auth::setLogoutCallback() -- set a callback for successful logout attempts
Auth::setSessionName() -- set a custom session name
Auth::setShowLogin() -- controls if the login form will be displayed. Turned on by default
Auth::sessionValidThru() --  get the time up to the session is valid
Auth::start() -- start authentication

Provides a framework for user authentication.

Introduction

Introduction -- A usage example

Auth tutorial

Our goal during this "mini tutorial" is to set up a system that secures your site with an easy to use authentication mechanism.

At the top of the site to secured, place the following code snippet:

Пример 29-1. Typical usage example for PEAR::Auth

require_once "Auth.php";

// Takes three arguments: last attempted username, the authorization
// status, and the Auth object. 
// We won't use them in this simple demonstration -- but you can use them
// to do neat things.
function loginFunction($username = null, $status = null, &$auth = null)
{
    /*
     * Change the HTML output so that it fits to your
     * application.
     */
    echo "<form method=\"post\" action=\"test.php\">";
    echo "<input type=\"text\" name=\"username\">";
    echo "<input type=\"password\" name=\"password\">";
    echo "<input type=\"submit\">";
    echo "</form>";
}

$options = array(
  'dsn' => "mysql://user:password@localhost/database",
  );
$a = new Auth("DB", $options, "loginFunction");

$a->start();

if ($a->checkAuth()) {
    /*
     * The output of your site goes here.
     */
}

This few lines of code instantiate the authentication system.

The first line in the above script includes the file from your PEAR directory. It contains all the necessary code to run PEAR::Auth. Next, we define a function to display the login form which the visitor of your page has to use to enter his login data. You can change all the HTML formatting in this function.

Since we want to use a database to verify the login data, we now create the variable $dsn, it contains a valid DSN string that will be used to connect to the database via PEAR::DB. For the default database table schema or to use a different storage container, please see below for more information.

After that we create the authentication object. The first parameter defines the name of the storage container. Because we want to use a database driven storage container, we pass "DB" here. The second parameter is the connection parameter for the container driver. We use the previously defined DSN string. The third parameter is the name of our function that we defined at the beginning of the script. It prints the login form.

Now our authentication object is initialized and we need to check if the user is logged in. This is done via the method checkAuth(). If it returns TRUE, we can pass the content of our page to the user.

In the following passages we cover more detailed information about the functions of PEAR::Auth.

This SQL statement creates a table usable under the default database authentication scheme using MySQL:

CREATE TABLE auth (
   username VARCHAR(50) default '' NOT NULL,
   password VARCHAR(32) default '' NOT NULL,
   PRIMARY KEY (username),
   KEY (password)
);

These are the table and field names necessary for working authentication. When hashing the passwords with the MD5 algorithm, which is the default encryption method in PEAR::Auth, the password column must be at least 32 characters long. When using another encryption method like DES ("UNIX crypt"), the column size has to be changed correspondingly.

Storage drivers

Storage drivers -- Introduction

Overview

PEAR::Auth uses a number of so called storage containers to store the login data. The following passages describe all of them. If the containers that come with the package don't fit your needs, it is easy to create custom ones, also.

Available Containers

Array

Storage container using a PHP Array.

DB

Storage container using PEAR DB.

DBLite

A simplified version of the DB container that only provides user authentication. No user management functions are provided.

File

Storage container using PEAR File_Passwd.

IMAP

Storage container for use against IMAP servers.

KADM5

Storage container for use against Kerberos V servers.

LDAP

Storage container for use against LDAP servers.

MDB

Storage container using PEAR MDB.

MDB2

Storage container using PEAR MDB2.

Multiple

Storage container for using multiple Auth_Containers in a fall through manner.

PEAR

Storage container for use against the PEAR website.

POP3

Storage container for use against a POP3 server.

RADIUS

Storage container for use against a RADIUS server.

SAP

Storage container for use against a SAP server.

SMBPasswd

Storage container using PEAR File_SMBPasswd.

SOAP

Storage container for use against a SOAP service using PEAR SOAP as the client.

SOAP5

Storage container for use against a SOAP service using PHP5 SOAP as the client.

vpopmail

Storage container using vpopmail.

Custom

Instructions on creating a custom storage container.

Logging

Logging -- Introduction

Overview

Since version 1.5.0 PEAR::Auth provides a facility for retrieving logs of its internal behaviour. This is implemented using PEAR::Log and its log observer components.

Auth provides two levels of log messages which map to the Log priority levels PEAR_LOG_INFO and PEAR_LOG_DEBUG.

PEAR_LOG_INFO messages provide basic information about Auth's decisions, for example user authentication successful/failed, rendering login screen.

PEAR_LOG_DEBUG messages provide detailed information about what is happening within the internals of Auth, for example which functions are called, logic tracking for the Authentication method, what SQL queries are being run against the database backends.

Example

Пример 29-1. Typical usage example for accessing the logs from PEAR::Auth

require_once "Auth.php";
require_once 'Log.php';
require_once 'Log/observer.php';

// Callback function to display login form
function loginFunction($username = null, $status = null, &$auth = null)
{
	/*
	 * Change the HTML output so that it fits to your
	 * application.
	 */
	echo "<form method=\"post\" action=\"".$_SERVER['PHP_SELF']."\">";
	echo "Username: <input type=\"text\" name=\"username\"><br/>";
	echo "Password: <input type=\"password\" name=\"password\"><br/>";
	echo "<input type=\"submit\">";
	echo "</form>";
}

class Auth_Log_Observer extends Log_observer {

	var $messages = array();

	function notify($event) {

		$this->messages[] = $event;

	}

}

$options = array(
		'enableLogging' => true,
		'cryptType' => 'md5',
		'users' => array(
			'guest' => md5('password'),
			),
		);
$a = new Auth("Array", $options, "loginFunction");

$infoObserver = new Auth_Log_Observer(PEAR_LOG_INFO);

$a->attachLogObserver($infoObserver);

$debugObserver = new Auth_Log_Observer(PEAR_LOG_DEBUG);

$a->attachLogObserver($debugObserver);

$a->start();

if ($a->checkAuth()) {
	/*
	 * The output of your site goes here.
	 */
	print "Authentication Successful.<br/>";
}

print '<h3>Logging Output:</h3>'
	.'<b>PEAR_LOG_INFO level messages:</b><br/>';

foreach ($infoObserver->messages as $event) {
	print $event['priority'].': '.$event['message'].'<br/>';
}

print '<br/>'
	.'<b>PEAR_LOG_DEBUG level messages:</b><br/>';

foreach ($debugObserver->messages as $event) {
	print $event['priority'].': '.$event['message'].'<br/>';
}

print '<br/>';

To enable logging pass the option "enableLogging" with the value TRUE in the options array in the second parameter to the Auth constructor.

To retrieve the log messages from Auth create a new subclass of Log_Observer that implements a notify() function to perform whatever actions you want on the log messages.

Once defined pass an instance of your new Log_Observer instance to Auth::attachLogObserver().

To limit the types of messages you receive in the Log_Observer pass either PEAR_LOG_INFO or PEAR_LOG_DEBUG as the first parameter to the Log_Observer. The default is PEAR_LOG_INFO. For more information on this filtering see the Log Documentation.

$observer = new My_Log_Observer(PEAR_LOG_DEBUG);

Заметка

This container has only been available since version 1.5.0.

Auth_Container_Array

Auth_Container_Array -- Authenticate against an array of usernames and passwords

Auth_Container_DB

Auth_Container_DB -- Authenticate against a database using DB

Auth_Container_DBLite

Auth_Container_DBLite -- Authenticate against a database using DB

Auth_Container_File

Auth_Container_File -- Authenticate a password file using File_Passwd

Auth_Container_IMAP

Auth_Container_IMAP -- Authenticate against an IMAP server

Auth_Container_KADM5

Auth_Container_KADM5 -- Authenticate against a Kerberos 5 server

Auth_Container_LDAP

Auth_Container_LDAP -- Authenticate against an LDAP server

LDAP Container

This storage container makes use of the ldap extension to load user data from an LDAP server.

The storage-specific argument for the Auth constructor() is an array of options.

Таблица 29-1. Available Options

OptionData TypeDefault valueDescription
"host" string "localhost" The host name or IP-adress to access
"port" integer 389 The port of the LDAP server to access
"url" string "" A fully qualified URL for specifying the protocol, url and port to connect to. It is useful for specifying ldaps://. Takes precedence over "host" and "port" options. Only works if PHP has been compiled against OpenLDAP 2+ libraries.
"version" integer 2 LDAP version to use, ususally 2 (default) or 3, must be an integer!
"referrals" boolean TRUE If set, determines whether the LDAP library automatically follows referrals returned by LDAP servers or not.
"binddn" string "" If set, searching for user will be done after binding as this user, if not set the bind will be anonymous. This is reported to make the container work with MS Active Directory, but should work with any server that is configured this way. This has to be a complete dn for now (basedn and userdn will not be appended).
"bindpw" string "" The password to use for binding with binddn.
"basedn" string "" The base DN of your server.
"userdn" string "" Gets prepended to basedn when searching for users.
"userscope" string "sub" Scope for user searching: one, sub (default), or base.
"userattr" string "uid" Defines the attribute to search for.
"userfilter" string "(objectClass=posixAccount)" Filter that will be added to the search filter this way: (&(userattr=username)(userfilter)).
"attributes" array array('') Array of additional attributes to fetch from entry. These will added to auth data and can be retrieved via Auth::getAuthData() . An empty array will fetch all attributes, array('') will fetch no attributes at all (default). If you add 'dn' as a value to this array, the user's DN that was used for binding will be added to auth data as well.
"attrformat" string "AUTH"

The returned format of the additional data defined in the 'attributes' option. Two formats are available.

LDAP returns data formatted in a multidimensional array where each array starts with a 'count' element providing the number of attributes in the entry, or the number of values for attributes. When set to this format, the only way to retrieve data from the Auth object is by calling getAuthData('attributes'). This was the default format before version 1.3.0.

AUTH returns data formatted in a structure more compliant with other Auth Containers, where each attribute element can be directly called by getAuthData() method from Auth. This became the default as of 1.3.0.

"groupdn" string "" Gets prepended to basedn when searching for group.
"groupattr" string "cn" The group attribute to search for.
"groupfilter" string "(objectClass=groupOfUniqueNames)" Filter that will be added to the search filter when searching for a group: (&(groupattr=group)(memberattr=username)(groupfilter)).
"memberattr" string "uniqueMember" The attribute of the group object where the user dn may be found.
"memberisdn" boolean TRUE Whether the memberattr is the dn of the user (default) or the value of userattr (usually uid).
"group" string "" The name of the group users have to be a member of to authenticate successfully.
"groupscope" string "sub" Scope for group searching: one, sub (default), or base.
"start_tls" boolean "false" Enable/disable the use of START_TLS encrypted connection.
"try_all" boolean FALSE If multiple entries are returned by the search attempt to authenticate against each entry in order or just the first one (default).
"debug" boolean FALSE Enable debug output.

When talking to a Microsoft ActiveDirectory server you have to use 'samaccountname' as the 'userattr' and follow special rules to translate the ActiveDirectory directory names into 'basedn'. The 'basedn' for the default 'Users' folder on an ActiveDirectory server for the ActiveDirectory Domain (which is not related to its DNS name) "win2000.example.org" would be: "CN=Users, DC=win2000, DC=example, DC=org" where every component of the domain name becomes a DC attribute of its own. If you want to use a custom users folder you have to replace "CN=Users" with a sequence of "OU" attributes that specify the path to your custom folder in reverse order. So the ActiveDirectory folder "win2000.example.org\Custom\Accounts" would become "OU=Accounts, OU=Custom, DC=win2000, DC=example, DC=org"

It seems that binding anonymously to an Active Directory is not allowed, so you have to set binddn and bindpw for user searching.

LDAP Referrals need to be set to false for AD to work sometimes.

Note also that if you want an encrypted connection to an MS LDAP server, then, on your webserver, you must specify "TLS_REQCERT never" in /etc/ldap/ldap.conf or in the webserver user's ~/.ldaprc (which may or may not be read depending on your configuration).

Auth_Container_MDB

Auth_Container_MDB -- Authenticate against a database using MDB

Auth_Container_MDB2

Auth_Container_MDB2 -- Authenticate against a database using MDB2

Заметка

By default, MDB2's default portability setting of MDB2_PORTABILITY_ALL is used. This setting may cause unexpected behaviour, such as field names being converted to lowercase regardless of their definition in the database schema. The "db_options" option can be used to override this, as shown in the following example.

Auth_Container_Multiple

Auth_Container_Multiple -- Authenticate against multiple Auth_Containers

Multiple

This container provides a facility to attempt to authenticate against multiple Auth_Containers in order.

If a container's getAuthData() returns true Auth_Container_Multiple will return true.

When a container's getAuthData() returns false Auth_Container_Multiple will continue on through the list of available containers until a successful login is found or the list of containers is expired.

On receipt of an error from getAuthData() Auth_Container_Multiple will abort checking further containers and return the error.

The storage-specific argument for the Auth constructor() is an array of container configurations. Each container configuration has the following options:

Пример 29-1. Example usage of Auth_Container_Multiple

require_once "Auth.php";
require_once 'Log.php';
require_once 'Log/observer.php';

// Callback function to display login form
function loginFunction($username = null, $status = null, &$auth = null)
{
	/*
	 * Change the HTML output so that it fits to your
	 * application.
	 */
	echo "<form method=\"post\" action=\"".$_SERVER['PHP_SELF']."\">";
	echo "Username: <input type=\"text\" name=\"username\"><br/>";
	echo "Password: <input type=\"password\" name=\"password\"><br/>";
	echo "<input type=\"submit\">";
	echo "</form>";
}

class Auth_Log_Observer extends Log_observer {

	var $messages = array();

	function notify($event) {

		$this->messages[] = $event;

	}

}

$options = array(
	'enableLogging' => true,
	array(
		'type' => 'Array',
		'options' => array(
			'cryptType' => 'md5',
			'users' => array(
				'guest' => md5('password'),
			),
		),
	),
	array(
		'type' => 'Array',
		'options' => array(
			'cryptType' => 'md5',
			'users' => array(
				'admin' => md5('password'),
			),
		),
	),
);
$a = new Auth("Multiple", $options, "loginFunction");

$infoObserver = new Auth_Log_Observer(PEAR_LOG_INFO);

$a->attachLogObserver($infoObserver);

$debugObserver = new Auth_Log_Observer(PEAR_LOG_DEBUG);

$a->attachLogObserver($debugObserver);

$a->start();

if ($a->checkAuth()) {
	/*
	 * The output of your site goes here.
	 */
	print "Authentication Successful.<br/>";
}

print '<h3>Logging Output:</h3>'
	.'<b>PEAR_LOG_INFO level messages:</b><br/>';

foreach ($infoObserver->messages as $event) {
	print $event['priority'].': '.$event['message'].'<br/>';
}

print '<br/>'
	.'<b>PEAR_LOG_DEBUG level messages:</b><br/>';

foreach ($debugObserver->messages as $event) {
	print $event['priority'].': '.$event['message'].'<br/>';
}

print '<br/>';

Заметка

This container has only been available since version 1.5.0.

Auth_Container_PEAR

Auth_Container_PEAR -- Authenticate against the PEAR website

PEAR Container

This container provides authentication services against the PEAR website (http://pear.php.net/) and it's developer accounts.

This container does not take an storage specific options.

Auth_Container_POP3

Auth_Container_POP3 -- Authenticate against a POP3 server

Auth_Container_RADIUS

Auth_Container_RADIUS -- Authenticate against a RADIUS server

RADIUS Container

You need Auth_RADIUS and the PECL radius in order to get this container to work.

The storage-specific argument for the Auth constructor() is an array of options.

Таблица 29-1. Available Options

OptionData TypeDefault valueDescription
"servers" array array("localhost", 0, "testing123", 3, 3)

Array of RADIUS servers, containing: host, port, shared secret, timeout, maxtries.

The host parameter specifies the server host, either as a fully qualified domain name or as a dotted-quad IP address in text form.

The port parameter specifies the UDP port to contact on the server. If port is given as 0, the library looks up the radius/udp entry in the network services database, and uses the port found there. If no entry is found, the library uses the standard RADIUS port for authentication (1812).

The shared secret for the server host is passed to the secret parameter. The RADIUS protocol ignores all but the leading 128 bytes of the shared secret.

The timeout for receiving replies from the server is passed to the timeout parameter, in units of seconds.

The maximum number of repeated requests to make before giving up is passed into the maxtries parameter.

At most 10 servers may be specified. When multiple servers are given, they are tried in round-robin fashion until a valid response is received, or until each server's maxtries limit has been reached.

"authtype" string "PAP"

The authentication method for validating the request. Possible values are: PAP, CHAP_MD5, MSCHAPv1, MSCHAPv2.

There are dependencies for the different methods. For all authentication methods except PAP you need the Crypt_CHAP package, when you are using MS-CHAP you need also the mhash extension.

Auth_Container_SAP

Auth_Container_SAP -- Authenticate against a SAP server

SAP Container

This container allows authentication against a SAP server using the SAPRFC extension available at http://saprfc.sourceforge.net/.

The storage-specific argument for the Auth constructor() is an array of options which are passed directly to the SAPRFC extension. None of the options are used internally, for more details see the SAPRFC's documentation.

Auth_Container_SMBPasswd

Auth_Container_SMBPasswd -- Authenticate a SAMBA smbpasswd file using File_SMBPasswd

SMBPasswd Container

This storage container provides authentication against SAMBA smbpasswd files. It makes use of the PEAR File_SMBPasswd package.

The storage-specific argument for the Auth constructor() is a string containing the filename of the SAMBA smbpasswd file to use.

Auth_Container_SOAP

Auth_Container_SOAP -- Authenticate against a SOAP service

Auth_Container_SOAP5

Auth_Container_SOAP5 -- Authenticate against a SOAP service

SOAP5 Container

This container makes use of the PHP SOAP extension's client to provide authentication against a SOAP service.

The storage-specific argument for the Auth constructor() is an array of options. In addition to the below options all options for the PHP SOAP Client can be passed in this array and they will be passed onto the client.

Auth_Container_vpopmail

Auth_Container_vpopmail -- Authenticate against a vpopmail service

vpopmail Container

This container uses an existing vpopmail service to validate the username and the password.

It does not require any storage-specific argument.

Custom Auth_Container

Custom Auth_Container -- Build a custom storage container

Auth_Frontend_HTML

Auth_Frontend_HTML -- Default login form

Overview

PEAR::Auth_Frontend_HTML provides a generic default login page for use with PEAR::Auth. When building your own login page it is a reasonable place to start as it includes all the required elements of the login form.

Константы

Константы -- предопределенные константы

AUTH_IDLED

-1

Returned if a session exceeds its idle time.

AUTH_EXPIRED

-2

Returned if a session has expired.

AUTH_WRONG_LOGIN

-3

Returned if the Auth Container in use is unable to validate the username/password pair supplied.

AUTH_METHOD_NOT_SUPPORTED

-4

Returned if the requested function is not implemented by the Auth Container in use.

AUTH_SECURITY_BREACH

-5

Returned if the advanced security checking detects a breach.

AUTH_CALLBACK_ABORT

-6

Returned if the checkAuth callback function aborted the session.

Auth::Auth()

Auth::Auth() -- constructor

Описание

Constructor for the authentication system.

The constructor will ensure that the PHP session management is started by calling session_start(). This is done as Auth requires a session to be active to operate correctly.

Параметр

string $storageDriver

Name of the storage driver that should be used, alternatively you can pass a custom Auth_Container object.

mixed $options

The options that are passed to the storage container.

string $loginFunction

The name of a user-defined function that prints the login screen. This function is passed three parameters when called $username, $status, &$auth. These are in order the previously attempted username, the status code that caused the previous auth attempt to fail and a reference to the Auth object itself.

boolean $showLogin

Defines if the login is optional or not.

Заметка

Эта функция не должна вызываться статически.

Пример

This example shows you how you can specifiy alternative names for the database table and the column names. In our example, we use the table myAuth, select the username from the field myUserColumn and the password from the field myPasswordColumn. The default values for this fields are auth, username and password. Note that you can also specify an existing DB object with the dsn parameter instead of a DSN.

This feature is necessary if you want to use PEAR::Auth with a database layout that is different from the one PEAR::Auth uses by default.

Пример

This example shows you how you can pass your own storage container to Auth.

If the storage containers supplied with Auth are not capable of fulfilling your requirements, you can easliy create your own storage container. Read the storage containers section for more info Introduction - The storage drivers

Auth::addUser()

Auth::addUser() -- add a new user

Описание

Add a new user to the Auth Container.

Параметр

string $username

the username of the new user

string $password

the password of the new user

mixed $additional = ''

additional options to be passed to the creation of the new user. Each Auth_Container has different options for these, please see the containers documentation for what is supported.

Возвращаемое значение

mixed - TRUE on success, a PEAR Error on failure.

Заметка

Эта функция не должна вызываться статически.

Not all Auth Containers implement this functionality.

Auth::attachLogObserver()

Auth::attachLogObserver() -- Attach a log observer instance to the internal Log object

Описание

Attach an instance of a Log_Observer to the internal Log object. This allows the internal logs to be accessed and used as you wish within your application.

Параметр

object &$observer

The instance of the Log_Observer to attach to the internal Log object.

Заметка

Эта функция не должна вызываться статически.

This function has only been available since version 1.5.0.

Auth::changePassword()

Auth::changePassword() -- change the password of a user

Описание

Change the password of a user within the Auth Container.

Параметр

string $username

the username of the user

string $password

the new password for the user

Возвращаемое значение

mixed - TRUE on success, a PEAR Error on failure.

Заметка

Эта функция не должна вызываться статически.

Not all Auth Containers implement this functionality.

Auth::checkAuth()

Auth::checkAuth() --  check if a session with valid authentication information exists

Описание

Checks if a session exists that contains valid authentication information.

Возвращаемое значение

boolean - If a session with valid authentication information exists, the function return TRUE. Otherwise it returns FALSE.

Заметка

Эта функция не должна вызываться статически.

Auth::getAuth()

Auth::getAuth() -- check for an authenticated user

Описание

Check if the user has been authenticated.

Возвращаемое значение

boolean - If the user has already been authenticated, the function returns TRUE. Otherwise it returns FALSE.

Заметка

Эта функция не должна вызываться статически.

Auth::getAuthData()

Auth::getAuthData() -- retrieve extra information stored within the auth session

Описание

This function retrieves the value of a previously registered data field.

Параметр

string $name

the name of the data field

Заметка

Эта функция не должна вызываться статически.

Auth::getStatus()

Auth::getStatus() -- get the current status of the auth session

Описание

Get the current status of the authentication session.

Возвращаемое значение

int - An Auth constant representing the current session state.

Заметка

Эта функция не должна вызываться статически.

См. также

"Auth Constants".

Auth::getUsername()

Auth::getUsername() -- get the username of the authenticated user

Описание

Get the username of the logged in user.

Возвращаемое значение

string - The username of the logged in user.

Заметка

Эта функция не должна вызываться статически.

Auth::listUsers()

Auth::listUsers() -- list available users

Описание

List all the users currently available within the current Auth Container.

Возвращаемое значение

array - An array of user details. Currently no consistency, see each Auth Container for details on how and what they return.

Заметка

Эта функция не должна вызываться статически.

Not all Auth Containers implement this functionality.

Auth::logout()

Auth::logout() -- logout an authenticated user

Описание

Logout any currently logged in user.

Заметка

Эта функция не должна вызываться статически.

Auth::removeUser()

Auth::removeUser() -- remove a user account

Описание

Remove a user from the Auth Container.

Параметр

string $username

the username of the user to remove

Возвращаемое значение

mixed - TRUE on success, a PEAR Error on failure.

Заметка

Эта функция не должна вызываться статически.

Not all Auth Containers implement this functionality.

Auth::setAdvancedSecurity()

Auth::setAdvancedSecurity() -- Enables advanced security features. Turned off by default

Описание

Enables advanced security features to make man in the middle attacks and session hijacking much harder. Cookies and java script must be enabled on the client browser for some of these features to function correctly.

Enables the following security features of auth

  • Detection of client ip address change or User-Agent header change if such a change is detected the user will be logged out

  • Each client request a special unique cookie is given to the client. He must present this cookie on his next request. This cookie changes on every request. If client does not present the valid cookie he will be logged out.

  • Enables challenge responce for the default login screen of auth. The user password will be hashed with javascript before sent back to the server. Prevents the user password being stolen using password sniffing tools. Password is hashed with a random key so the md5 hash is not subject to brute force password cracking. This will only work for storage containers which support challenge responce password authenthication. Currently only the DB, MDB and MDB2 containers support this for md5 and clear text passwords

Замечание: This method is available since 1.3.0

Параметр

boolean $flag

TRUE if you want to enable advanced security features FALSE if you want to disable them.

Заметка

Эта функция не должна вызываться статически.

Auth::setAllowLogin()

Auth::setAllowLogin() -- Controls if the user will be allowed to login. Turned on by default

Описание

Controls if auth will process the post variables and attempt to login the user from those pages. For better security of your application it is recomended to disable login in all pages except your login page.

Параметр

boolean $allowLogin

If you want to allow login set this to TRUE otherwise set it to FALSE.

Заметка

Эта функция не должна вызываться статически.

This method is available since 1.3.0

Auth::setAuth()

Auth::setAuth() -- set a specific user to be marked as logged in

Описание

Mark the session up to indicate that the username supplied has successfully logged in. Although normally used for internal purposes this function can be used to fake a login.

Параметр

string $name

the name of the data field

Заметка

Эта функция не должна вызываться статически.

This function will also call session_regenerate_id() so as to prevent session fixation attacks.

Auth::setAuthData()

Auth::setAuthData() -- store extra information with the Auth session

Описание

This function allows the registration of extra information to be stored allowing with the authentication data.

Параметр

string $name

the name of the data field

mixed $value

the value of the data field

boolean $overwrite

whether to overwrite the value of the data field if it already exists.

Заметка

Эта функция не должна вызываться статически.

Auth::setCheckAuthCallback()

Auth::setCheckAuthCallback() -- set a callback to run when ever session validity is checked

Описание

This function sets a callback function which is called whenever the validity of a logged in session is checked. This callback can be used to perform actions like checking the authentication source to see if the logged in user is still enabled.

The callback function will be passed two parameters, the username that successfully logged in and a reference to the Auth object. The callback function should return a boolean depending upon whether the session should continue or not. TRUE to allow the session to continue, FALSE to abort the session.

If the session is aborted by this callback the status will be set to AUTH_CALLBACK_ABORT.

Параметр

string $checkAuthCallback

the call back function to use

Заметка

Эта функция не должна вызываться статически.

Auth::setExpire()

Auth::setExpire() -- set expiration time for authentication

Описание

With this function you can set the maximum expire time that is used by auth to a new value.

Параметр

integer $time

expiration time, number of seconds

boolean $add

if TRUE $time is added to the existing expiration time, if FALSE the exitsing time value will be replaced.

Заметка

Эта функция не должна вызываться статически.

Auth uses PHP's session mechanism to recognize users between http calls. Setting Auth's expiry time larger than the session timeout will still expire the session to the time the php session expires.

Auth::setFailedLoginCallback()

Auth::setFailedLoginCallback() -- set a callback for failed login attempts

Описание

This function sets a callback function which is called upon failed login of a user account.

The callback function will be passed two parameters, the username that failed to login and a reference to the Auth object.

Параметр

string $loginFailedCallback

the call back function to use

Заметка

Эта функция не должна вызываться статически.

Auth::setIdle()

Auth::setIdle() -- set maximum idle time for authentication

Описание

With this function one can set the maximum idle time to a new value. The term "idle time" describes the maximum time interval (in seconds) between two actions by the user. If the maximum idle time is reached, the user will be automatically logged out. If on the other hand the user performs any action within the maximum idle time interval, the idle time is reset.

Параметр

integer $time

idle time in seconds

boolean $add

if TRUE $time is added to the existing idle time, if FALSE the existing time value will be replaced.

Заметка

Эта функция не должна вызываться статически.

Auth::setLoginCallback()

Auth::setLoginCallback() -- set a callback for successful login attempts

Описание

This function sets a callback function which is called upon successful login of a user account.

The callback function will be passed two parameters, the username that successfully logged in and a reference to the Auth object.

Параметр

string $loginCallback

the call back function to use

Заметка

Эта функция не должна вызываться статически.

Auth::setLogoutCallback()

Auth::setLogoutCallback() -- set a callback for successful logout attempts

Описание

This function sets a callback function which is called upon successful logout of a user account.

The callback function will be passed two parameters, the username that successfully logged out and a reference to the Auth object.

Параметр

string $loginCallback

the call back function to use

Заметка

Эта функция не должна вызываться статически.

Auth::setSessionName()

Auth::setSessionName() -- set a custom session name

Описание

This function can set a customized name for the session that is created during the login process. The default for this session name is "PHPSESSID".

Параметр

string $name

the session name to use

Заметка

Эта функция не должна вызываться статически.

You have to use setSessionName(), if you are running two or more different applications with Auth on the same domain. If you don't use this function, a user who has once logged in at one of the applications can also use the other applications without logging in again!

Auth::setShowLogin()

Auth::setShowLogin() -- controls if the login form will be displayed. Turned on by default

Описание

Controls if the login page will be displayed to the user. Normally you might need to display the login form only on a certain page of your web application.

Параметр

boolean $showLogin

true if you want to display the login form and false if you want to hide it.

Заметка

Эта функция не должна вызываться статически.

This is equivalent to the 4th paramether of Auth::Auth()

Auth::sessionValidThru()

Auth::sessionValidThru() --  get the time up to the session is valid

Описание

This method returns the time in seconds after which the idle time of the current authentication session has reached its limit, which will cause the user to be logged out automatically. If no maximum idle time is set, which is the default configuration of PEAR::Auth, this method will return 0.

Заметка

Эта функция не должна вызываться статически.

Auth::start()

Auth::start() -- start authentication

Описание

Start the authentication process. To do this Auth checks for an existing session and checks it's validity. If there is no existing session or the previous session has been ended for some reason then the login form is generated either via the specified callback or using the default form implemented in Auth_Frontend_HTML.

Заметка

Эта функция не должна вызываться статически.


Auth_HTTP

Содержание
Introduction -- to HTTP based authentication
Auth_HTTP::Auth_HTTP() -- constructor
Auth_HTTP Example -- Example: A simple password protected page
Auth_HTTP Example 2 -- Example: A password protected page with multiple rows fetch and md5 password
Auth_HTTP::getAuth() -- check for an authenticated user
Auth_HTTP::getStatus() -- returns informations about the current authentication status
Auth_HTTP::start() -- start authentication

Provides a framework for user authentication (aka an "User-Login") based on the HTTP

Introduction

Introduction -- to HTTP based authentication

Instead of generating an HTML driven form like PEAR::Auth does, this class sends header commands to the clients which cause them to present a login box like they are e.g. used in Apache's .htaccess mechanism.

Starting with Auth_HTTP 2.1.0, HTTP Digest Authentication (RFC2617) is experimentally supported.

Auth_HTTP::Auth_HTTP()

Auth_HTTP::Auth_HTTP() -- constructor

Описание

Constructor for the authentication system

Параметр

string $storageDriver

name of the storage driver that should be used

mixed $options

a string containing some login information or an array containing a bunch of options for the storage driver

Заметка

Эта функция не должна вызываться статически.

Auth_HTTP Example

Auth_HTTP Example -- Example: A simple password protected page

Пример

<?php

// example of Auth_HTTP basic implementation 

require_once("Auth/HTTP.php");

// setting the database connection options
$AuthOptions = array(
'dsn'=>"pgsql://test:test@localhost/testdb",
'table'=>"testable",                            // your table name 
'usernamecol'=>"username",			// the table username column
'passwordcol'=>"password",			// the table password column
'cryptType'=>"none",				// password encryption type in your db
);


$a = new Auth_HTTP("DB", $AuthOptions);

$a->setRealm('yourrealm');			// realm name
$a->setCancelText('<h2>Error 401</h2>');        // error message if authentication fails
$a->start();					// starting the authentication process


if($a->getAuth())				// checking for autenticated user 
{
	echo "Hello $a->username welcome to my secret page";
	
};

?>

Auth_HTTP Example 2

Auth_HTTP Example 2 -- Example: A password protected page with multiple rows fetch and md5 password

Пример

<?php  
// example of Auth_HTTP implementation with encrypted password and multiple columns fetch

require_once("Auth/HTTP.php");

// setting the database connection options
$AuthOptions = array(
'dsn'=>"pgsql://test:test@localhost/testdb",
'table'=>"testable",                            // your table name 
'usernamecol'=>"username",			// the table username column
'passwordcol'=>"password",			// the table password column
'cryptType'=>"md5",				// password encryption type in your db
'db_fields'=>"*",				// enabling fetch for other db columns
);


$a = new Auth_HTTP("DB", $AuthOptions);

$a->setRealm('yourrealm');			// realm name
$a->setCancelText('<h2>Error 401</h2>');        // error message if authentication fails
$a->start();					// starting the authentication process


if($a->getAuth())				// checking for autenticated user 
{
	echo "Hello $a->username welcome to my secret page <BR>";
	echo "Your details on file are: <BR>";
	echo $a->getAuthData('userid');		// retriving other details from the database row
	echo $a->getAuthData('telephone');      // in this example the user id, telephone number
	echo $a->getAuthData('email');		// and email address
};
?>

Auth_HTTP::getAuth()

Auth_HTTP::getAuth() -- check for an authenticated user

Описание

Check if the user has been authenticated.

Возвращаемое значение

boolean - If the user has already been authenticated, the function returns TRUE. Otherwise it returns FALSE.

Заметка

Эта функция не должна вызываться статически.

Auth_HTTP::getStatus()

Auth_HTTP::getStatus() -- returns informations about the current authentication status

Описание

This function returns the current status of PEAR::Auth. The return values are constants that are defined by PEAR Auth.

Возвращаемое значение

string - possible values are AUTH_IDLED, AUTH_EXPIRED, AUTH_EXPIRED

Заметка

Эта функция не должна вызываться статически.

Auth_HTTP::start()

Auth_HTTP::start() -- start authentication

Описание

Start the authentication process.

Заметка

Эта функция не должна вызываться статически.


Глава 30. Тестирование

Предоставляет пакеты для тестирования и профилирования


Глава 31. Кэширование

Предоставляет пакеты для создания кэширования.



Cache_Lite

Содержание
Introduction -- Introduction to Cache_Lite
constructor Cache_Lite::Cache_Lite() -- Constructor
Cache_Lite::get() -- Test if a cache is available and (if yes) return it
Cache_Lite::save() -- Save some data in a cache file
Cache_Lite::remove() -- Remove a cache file
Cache_Lite::clean() -- Clean the cache
Cache_Lite::setToDebug() -- Set to debug mode
Cache_Lite::setLifeTime() -- Set a new life time
Cache_Lite::saveMemoryCachingState() -- 
Cache_Lite::getMemoryCachingState() -- 
Cache_Lite::lastModified() -- Return the cache last modification time
Cache_Lite::raiseError() -- Trigger a PEAR error
Cache_Lite::extendLife() -- Extend the life of a valid cache file
constructor Cache_Lite_Output::Cache_Lite_Output() -- Constructor
Cache_Lite_Output::start() -- Test if a cache is available and (if yes) return it to the browser. Else, the output buffering is activated.
Cache_Lite_Output::end() -- Stop the output buffering started by the start() method and store the output to a cache file
constructor Cache_Lite_Function::Cache_Lite_Function() -- Constructor
Cache_Lite_Function::call() -- Calls a cacheable function or method (or not if there is already a cache for it)
Cache_Lite_Function::drop() -- Drop a cache file
constructor Cache_Lite_File::Cache_Lite_File() -- Constructor
Cache_Lite_File::get() -- Test if a cache is available and (if yes) return it

Cache_Lite provides a fast, light and safe cache system. It's optimized for file containers and protected against cache corruptions (because it uses file locking and/or hash tests).

Introduction

Introduction -- Introduction to Cache_Lite

Описание

PEAR::Cache_Lite is a little cache system. It's optimized for high traffic websites so it is really fast and safe (because it uses file locking and/or anti-corruption tests).

Note : An independant documentation of Cache_Lite is available in chinese on this page.

Goals and technical details

speed

Before all, PEAR::Cache_Lite has to be extremely fast. That returns the use of PEAR possible on sites with high traffic without falling in hi-level hardware solutions.

You can find more details about cache_lite technical choices on the this document. but the main idea is to include PEAR.php file ONLY when an error occurs (very rare).

simplicity

Because the cache system is often embedded in the application layer, PEAR::Cache_Lite kernel has to be small and flexible with an adapted licence (LGPL). Advanced functionnalities can be found in files that extends the core.

security

On high traffic websites, the cache system has to be really protected against cache files corruptions (because of concurrent accesses in read/write mode). Very few cache systems offer a protection against this problem.

File locking is not a perfect solution because it is useless with NFS or multithreaded servers. So in addition to it, PEAR::Cache_Lite offers two fully transparent mechanisms (based on hash keys) to guarantee the security of the data in all circumstances. Just have a look at the link given in the previous paragraph for more details.

Usage

general usage

Every module of Cache_Lite follows the same philosophy.

Parameters (others than default ones) are passed to the constructor by using an associative array.

A cache file is identified by a cache ID (and eventually a group). For obvious flexibility reasons, the logic of IDs choice is left to the developer.

In the following, we will use the term "group" as a pool of cache files and the term "block" as a piece of an HTML page.

core

Let's start with a simple example : the page is built then recovered in an unique variable (string):
<?php

// Include the package
require_once('Cache/Lite.php');

// Set a id for this cache
$id = '123';

// Set a few options
$options = array(
    'cacheDir' => '/tmp/',
    'lifeTime' => 3600
);

// Create a Cache_Lite object
$Cache_Lite = new Cache_Lite($options);

// Test if thereis a valide cache for this id
if ($data = $Cache_Lite->get($id)) {

    // Cache hit !
    // Content is in $data
    // (...)

} else { // No valid cache found (you have to make the page)

    // Cache miss !
    // Put in $data datas to put in cache
    // (...)
    $Cache_Lite->save($data);

}

?>

If you wish use a cache per block and not a global cache, take as example the following script:
<?php
require_once('Cache/Lite.php');

$options = array(
    'cacheDir' => '/tmp/',
    'lifeTime' => 3600
);

// Create a Cache_Lite object
$Cache_Lite = new Cache_Lite($options);

if ($data = $Cache_Lite->get('block1')) {
    echo($data);
} else {
    $data = 'Data of the block 1';
    $Cache_Lite->save($data);
}

echo('<br><br>Non cached line !<br><br>');

if ($data = $Cache_Lite->get('block2')) {
    echo($data);
} else {
    $data = 'Data of the block 2';
    $Cache_Lite->save($data);
}

?>

core

However, it is not always possible to recover all the contents of a page in a single string variable. Thus Cache_Lite_Output comes to our help :
<?php

require_once('Cache/Lite/Output.php');

$options = array(
    'cacheDir' => '/tmp/',
    'lifeTime' => 10
);

$cache = new Cache_Lite_Output($options);

if (!($cache->start('123'))) {
    // Cache missed...
    for($i=0;$i<1000;$i++) { // Making of the page...
        echo('0123456789');
    }
    $cache->end();
}

?>

The idea is the same for a per block usage :
<?php

require_once('Cache/Lite/Output.php');

$options = array(
    'cacheDir' => '/tmp/',
    'lifeTime' => 10
);

$cache = new Cache_Lite_Output($options);

if (!($cache->start('block1'))) {
    // Cache missed...
    echo('Data of the block 1 !');
    $cache->end();
}

echo('Non cached line !');

if (!($cache->start('block2'))) {
    // Cache missed...
    echo('Data of the block 2 !');
    $cache->end();
}

?>

IMPORTANT NOTE

For a maximum efficiency with Cache_Lite, do not systematically include every package the page needs. ONLY load the modules you need when the page is not in the cache (and has to be recomputed) by using a conditionnal inclusion.

The BAD way :
<?php
   require_once("Cache/Lite.php");
   require_once("...")
   require_once("...")
   // (...)
   $cache = new Cache_Lite();
   if ($data = $Cache_Lite->get($id)) { // cache hit !
       echo($data);
   } else { // page has to be (re)constructed in $data
       // (...)
       $Cache_Lite->save($data);
   }
?>

Here is the good way (often more than twice faster) :
<?php
   require_once("Cache/Lite.php");
   // (...)
   $cache = new Cache_Lite();
   if ($data = $Cache_Lite->get($id)) { // cache hit !
       echo($data);
   } else { // page has to be (re)constructed in $data
       require_once("...")
       require_once("...")
       // (...)
       $Cache_Lite->save($data);
   }
?>

Conclusion

To go further with Cache_Lite, have a look at examples and technical details bundled with the package.

constructor Cache_Lite::Cache_Lite()

constructor Cache_Lite::Cache_Lite() -- Constructor

Описание

The constructor of the Cache_Lite core class. You can give an associative array as an argument to set a lot of options.

Параметр

array $options

associative array to set a lot of options

Таблица 31-1.

OptionData TypeDefault ValueDescription
cacheDir string /tmp/ directory where to put the cache file (with a trailing slash at the end)
caching boolean TRUE enable / disable caching
lifeTime integer 3600 cache lifetime in seconds (since 1.6.0beta 1, you can use a null value for an eternal cache lifetime)
fileLocking boolean TRUE enable / disable fileLocking. Can avoid cache corruption under bad circumstances.
writeControl boolean TRUE enable / disable write control. Enable write control will lightly slow the cache writing but not the cache reading. Write control can detect some corrupt cache files but maybe it's not a perfect control.
readControl boolean TRUE enable / disable read control. If enabled, a control key is embeded in cache file and this key is compared with the one calculated after the reading
readControlType string crc32 Type of read control (only if read control is enabled). Must be 'md5' (for a md5 hash control (best but slowest)), 'crc32' (for a crc32 hash control (lightly less safe but faster)) or 'strlen' (for a length only test (fastest))
pearErrorMode integer CACHE_LITE_ERROR_RETURN pear error mode (when raiseError is called) (CACHE_LITE_ERROR_RETURN for just returning a PEAR_Error object or CACHE_LITE_ERROR_DIE for immediate stop of the script (good for debug) )
fileNameProtection boolean TRUE file Name protection (if set to true, you can use any cache id or group name, if set to false, it can be faster but cache ids and group names will be used directly in cache file names so be carefull with special characters...)
automaticSerialization boolean FALSE enable / disable automatic serialization (it can be used to save directly datas which aren't strings but it's slower)
memoryCaching boolean FALSE enable / disable "Memory Caching" (NB : there is no lifetime for memory caching, only the end of the script)
onlyMemoryCaching boolean FALSE enable / disable "Only Memory Caching" (if enabled, files are not used anymore)
memoryCachingLimit integer 1000 max number of records to store into memory caching
automaticCleaningFactor integer 0 Disable / Tune the automatic cleaning process. The automatic cleaning process destroy too old (for the given life time) cache files when a new cache file is written. 0 means "no automatic cache cleaning", 1 means "systematic cache cleaning" (slow), x>1 means "automatic cleaning randomly 1 times on x cache writes". A value between 20 and 200 is maybe a good start.
hashedDirectoryLevel integer 0 Set the hashed directory structure level. 0 means "no hashed directory structure", 1 means "one level of directory", 2 means "two levels"... This option can speed up Cache_Lite only when you have many thousands of cache file. Only specific benchs can help you to choose the perfect value for you. Maybe, 1 or 2 is a good start.
errorHandlingAPIBreak boolean FALSE If set to true, it introduces a little API break but the error handling is better in CACHE_LITE_ERROR_RETURN mode (specially with the save() method which can return a PEAR_Error object).

Throws

No exceptions thrown.

Заметка

Эта функция не должна вызываться статически.

Cache_Lite::get()

Cache_Lite::get() -- Test if a cache is available and (if yes) return it

Описание

One of the main method of Cache_Lite : test the validity of a cache file and return it if it's available (FALSE else)

Параметр

string $id

cache id

string $group

name of the cache group

boolean $doNotTestCacheValidity

if set to TRUE, the cache validity won't be tested

Возвращаемое значение

returns data of the cache (or false if no cache available)

Заметка

Эта функция не должна вызываться статически.

Cache_Lite::save()

Cache_Lite::save() -- Save some data in a cache file

Описание

save the given data (which has to be a string if automaticSerialization is set to FALSE (default)).

Параметр

string $data

data to put in a cache file (can be another type than strings if automaticSerialization is TRUE).

string $id

cache id

string $group

name of the cache group

Возвращаемое значение

returns true if no problem

Заметка

Эта функция не должна вызываться статически.

Cache_Lite::remove()

Cache_Lite::remove() -- Remove a cache file

Описание

remove the given cache file (specified with its id and group)

Параметр

string $id

cache id

string $group

name of the cache group

Возвращаемое значение

returns true if no problem

Заметка

Эта функция не должна вызываться статически.

Cache_Lite::clean()

Cache_Lite::clean() -- Clean the cache

Описание

if no group is specified all cache files will be destroyed ; else only cache files of the specified group will be destroyed

Параметр

string $group

name of the cache group

string $mode

flush cache mode : 'old' (clean too old cache files for the current lifetime), 'ingroup' (clean all cache files for the given group), 'notingroup' (clean all the cache files except for the given group), [since 1.5.0 beta] 'callback_myFunc' (call the function 'myFunc' with the complete path file and the group in parameters, if the callback return 'true', the cache file is deleted).

Возвращаемое значение

returns true if no problem

Заметка

Эта функция не должна вызываться статически.

Cache_Lite::setToDebug()

Cache_Lite::setToDebug() -- Set to debug mode

Описание

when an error is found, the script will stop and the message will be displayed (in debug mode only) ; same effect than pearErrorMode option in the constructor

Заметка

Эта функция не должна вызываться статически.

Cache_Lite::setLifeTime()

Cache_Lite::setLifeTime() -- Set a new life time

Описание

change the cache life time

Параметр

integer $newLifeTime

new life time (in seconds)

Throws

throws no exceptions thrown

Заметка

Эта функция не должна вызываться статически.

Cache_Lite::saveMemoryCachingState()

Cache_Lite::saveMemoryCachingState() -- 

Описание

save the current state of the memory caching array into a classical cache file

Параметр

string $id

cache id

string $group

name of the cache group

Заметка

Эта функция не должна вызываться статически.

Cache_Lite::getMemoryCachingState()

Cache_Lite::getMemoryCachingState() -- 

Описание

load a previously saved state of a memory caching array from a classical cache file

Параметр

string $id

cache id

string $group

name of the cache group

boolean $doNotTestCacheValidity

if set to TRUE, the cache validity won't be tested

Заметка

Эта функция не должна вызываться статически.

Cache_Lite::lastModified()

Cache_Lite::lastModified() -- Return the cache last modification time

Описание

[ONLY FOR CACHE_LITE HACKERS] return the cache last modification time

Возвращаемое значение

returns last modification time

Заметка

Эта функция не должна вызываться статически.

Cache_Lite::raiseError()

Cache_Lite::raiseError() -- Trigger a PEAR error

Описание

include dynamically the PEAR.php file and trigger a PEAR error

To improve performances, the PEAR.php file is included dynamically. The file is so included only when an error is triggered. So, in most cases, the file isn't included and perfs are much better.

Параметр

string $msg

error message

integer $code

error code

Заметка

Эта функция не должна вызываться статически.

Cache_Lite::extendLife()

Cache_Lite::extendLife() -- Extend the life of a valid cache file

Описание

[since Cache_Lite-1.7.0beta2] Extend the life of an existent cache file. The cache file is "touched", so it starts a new lifetime period. See this feature request for more details.

Throws

No exceptions thrown.

Заметка

Эта функция не должна вызываться статически.

constructor Cache_Lite_Output::Cache_Lite_Output()

constructor Cache_Lite_Output::Cache_Lite_Output() -- Constructor

Описание

The constructor of the Cache_Lite_Output class. You can give an associative array as an argument to set a lot of options.

Параметр

array $options

associative array to set a lot of options (see Cache_Lite constructor for details)

Заметка

Эта функция не должна вызываться статически.

Cache_Lite_Output::start()

Cache_Lite_Output::start() -- Test if a cache is available and (if yes) return it to the browser. Else, the output buffering is activated.

Описание

Test if a cache is available and (if yes) return it to the browser. Else, the output buffering is activated.

Параметр

string $id

cache id

string $group

name of the cache group

boolean $doNotTestCacheValidity

if set to TRUE, the cache validity won't be tested

Возвращаемое значение

returns true if the cache is hit (false else)

Заметка

Эта функция не должна вызываться статически.

Cache_Lite_Output::end()

Cache_Lite_Output::end() -- Stop the output buffering started by the start() method and store the output to a cache file

Описание

Stop the output buffering started by the start() method and store the output to a cache file

Заметка

Эта функция не должна вызываться статически.

constructor Cache_Lite_Function::Cache_Lite_Function()

constructor Cache_Lite_Function::Cache_Lite_Function() -- Constructor

Описание

The constructor of the Cache_Lite_Output class. You can give an associative array as an argument to set a lot of options.

Заметка

Эта функция не должна вызываться статически.

Cache_Lite_Function::call()

Cache_Lite_Function::call() -- Calls a cacheable function or method (or not if there is already a cache for it)

Описание

call the given function with given arguments only if there is no cache about it ; else, the output of the function is read from the cache then send to the browser and the return value if read also from the cache and returned.

Возвращаемое значение

returns result of the function/method

Заметка

Эта функция не должна вызываться статически.

Cache_Lite_Function::drop()

Cache_Lite_Function::drop() -- Drop a cache file

Описание

[since Cache_Lite 1.6.0beta1] Drop the cache file of the corresponding function call with given arguments.

Возвращаемое значение

returns true if ok

Заметка

Эта функция не должна вызываться статически.

constructor Cache_Lite_File::Cache_Lite_File()

constructor Cache_Lite_File::Cache_Lite_File() -- Constructor

Описание

The constructor of the Cache_Lite_File class. You can give an associative array as an argument to set a lot of options.

Параметр

array $options

associative array to set a lot of options (see Cache_Lite constructor for details). Be carefull, with Cache_Lite_File, there is an additional "mandatory option" described on the following table.

Заметка

Эта функция не должна вызываться статически.

Cache_Lite_File::get()

Cache_Lite_File::get() -- Test if a cache is available and (if yes) return it

Описание

test the validity of a cache file and return it if it's available (FALSE else)

Параметр

string $id

cache id

string $group

name of the cache group

Возвращаемое значение

returns data of the cache (or false if no cache available)

Заметка

Эта функция не должна вызываться статически.


Глава 32. Конфигурация

Предоставляет пакеты для управления конфигурациямию


Config

Содержание
Introduction --  What Config can do
Editing a configuration --  How to manipulate your configuration content
Available Containers --  Supported formats
Config::Config() -- constructor
Config::getRoot() -- Return root container for config object
Config::isConfigTypeRegistered() -- Returns TRUE if container is registered
Config::parseConfig() -- Parse datasource contents
Config::registerConfigType() -- Registers a custom Config container
Config::setRoot() -- Set content of root Config_container object
Config::writeConfig() -- Write container content to datasource
Config_Container::Config_Container() -- Constructor
Config_Container::addItem() -- Add item to this item.
Config_Container::countChildren() -- Count children of container
Config_Container::createBlank() -- Add blank line to item
Config_Container::createComment() -- Add comment to item
Config_Container::createDirective() -- Add directive to item
Config_Container::createItem() -- Create new child for section item
Config_Container::createSection() -- Add section to item
Config_Container::getAttribute() -- Get attribute value of item
Config_Container::getAttributes() -- Get item attributes
Config_Container::getChild() -- Return child object at specified index.
Config_Container::getContent() -- Get item content
Config_Container::getItem() -- Tries to find specific items
Config_Container::getItemIndex() -- Return item index in its parent children array
Config_Container::getItemPosition() -- Return item rank in its parent children array
Config_Container::getName() -- Get item name
Config_Container::getParent() -- Return item parent object
Config_Container::getType() -- Get item type
Config_Container::isRoot() -- Check for root item
Config_Container::removeItem() -- Deletes an item from the object
Config_Container::searchPath() -- Finds a node using XPATH like format
Config_Container::setAttributes() -- Set item attributes
Config_Container::setContent() -- Set item content
Config_Container::setDirective() -- Set child directive content or create new directive
Config_Container::setName() -- Set item name
Config_Container::setType() -- Set item type
Config_Container::toArray() -- Return key/value pair array of container and its children
Config_Container::toString() -- Return string representation
Config_Container::updateAttributes() -- Update item attributes
Config_Container::writeDatasrc() -- Write item to file

The Config package provides methods for configuration manipulation.

Introduction

Introduction --  What Config can do

Introduction

Config helps you manipulate your configuration whether they are stored in XML files, PHP arrays or other kind of datasources. It supports these features:

  • Parse different configuration formats.

  • Manipulate sections, directives, comments, blanks the way you want.

  • Write them back to a datasource in your preferred format.

The Config object acts as a container for other Config_Container objects. It doesn't do much but makes handling IO operations easier. It contains the root Config_Container object which in turn contains a child Config_Container object. Config_Container objects store references to their parent and have an array of children. This structure makes it easy to access the different containers and their contents.

A Config_Container object can be of different type:

  • Section: a section contains other Config_Container objects.

  • Directive: a directive does not contain any other object but has content and a name. See them as key-value pairs.

  • Comment: just like directives, comments have content but they don't have a name. They are rendered in a special way according to the configuration type you choosed.

  • Blank: they don't have neither content or name but are used to indicate blank lines if your renderer uses them.

When using the Config package, most of the work is done with Config_Container objects.

The above example illustrates how Config and Config_Container can interact. There are other ways. You could have for example first created the Config object and then used $config->getRoot() to add sections and directives to the returned object reference.

For more information, You can read API doc, sample of package, tests of package, and a great tutorial of DevShed about the Config package.

Editing a configuration

Editing a configuration --  How to manipulate your configuration content

Create configuration content

There are many ways to create content in your Config object. You can simply pass it an array like it is shown in the example below:

You can also ask Config to look for a file on your filesystem and try to parse it. You would then do it like this. This example assumes you have a valid XML file:
At the moment, Config can parse XML, PHP arrays, ini files, Apache conf and other generic type of configurations with comments and key-value pairs.

Of course, it is also possible to create the configuration from scratch as shown in the previous section example.

Available Containers

Available Containers --  Supported formats

Available Containers

Apache

Parses and saves Apache configuration files. No options are provided by this container.

GenericConf

Generic configuration files. The equals, comment start and new line characters in the parser can be customised to match your prefered configuration format.

IniCommented

Parses standard INI files, maintaining comments within the file. No options are available for this container.

IniFile

Parse standard INI files using PHP's in built parse_ini_file(). Does not read in comments. No options are available for this container.

PHPArray

Parses PHP Array structures. Can read from a PHP Source file or from an in memory array. Due to technical limitations, this container does not parse blank lines or comments when reading from a configuration file, therefore any information contained within PHP comments will be lost.

Внимание

Since config files containing php arrays are just included using the standard php methods, code comments and structure will be lost when saving.

PHPConstants

Parses a set of PHP define() from a PHP source file. Comments are maintained by this container, although blank lines will be lost. There are no options for this container.

XML

Parses a XML file using XML_Parser.

Config::Config()

Config::Config() -- constructor

Описание

The Config constructor, it creates a root Config_Container.

Config::getRoot()

Config::getRoot() -- Return root container for config object

Описание

This method returns a reference to the root Config_Container object in the Config object. Use the returned Config_Container object reference to manipulate your configuration data.

Возвращаемое значение

object - a reference to config's root container object

Заметка

Эта функция не должна вызываться статически.

Config::isConfigTypeRegistered()

Config::isConfigTypeRegistered() -- Returns TRUE if container is registered

Описание

This method checks if the required container type exists in $GLOBALS['CONFIG_TYPES'].

Параметр

string $configType

Type of config (php array, xml, inifile...)

Возвращаемое значение

bool - TRUE if registered, FALSE otherwise.

Заметка

Эта функция не должна вызываться статически.

Config::parseConfig()

Config::parseConfig() -- Parse datasource contents

Описание

This method will parse the datasource given and fill the root Config_Container object with other Config_Container objects. It will return a reference to the root Config_Container object or a PEAR_Error if something went wrong.

Параметр

mixed $datasrc

Datasource to parse. For most containers, it is a file path. For the PHP array parser, it can be an array too.

string $configType

Type of configuration to parse

array $options

Options for the parser

Возвращаемое значение

object - a reference to Config_Container object

Заметка

Эта функция не должна вызываться статически.

Config::registerConfigType()

Config::registerConfigType() -- Registers a custom Config container

Описание

This method registers a new container type with the Config class.

Параметр

string $configType

The name of the configuration type.

array $configInfo

An array defining the file containing the container's class definition and the class name. The format for this array is as follows:
$configInfo = array('path/to/Name.php',             // The path to the source file for the class.
                    'Config_Container_Class_Name'   // The name of the container class.
                   );

If omitted, the default values are:
$configInfo = array("Config/Container/$configType.php",
                    "Config_Container_$configType"
                   );

Возвращаемое значение

mixed - Возвращает TRUE при удаче и PEAR_Error в обратном случае.

Config::setRoot()

Config::setRoot() -- Set content of root Config_container object

Описание

This method will replace the current child of the root Config_Container object by the given object.

Параметр

object $rootContainer

Container to be used as the first child of root

Возвращаемое значение

boolean - Возвращает TRUE в случае успеха и FALSE при неудаче.

Заметка

Эта функция не должна вызываться статически.

Config::writeConfig()

Config::writeConfig() -- Write container content to datasource

Описание

This method will call the root Config_Container::writeDatasrc() method which in turn will try to write the Config contents to the datasource.

Параметр

mixed $datasrc

Datasource to write to

string $configType

Type of configuration for writer

array $options

Options for writer

Возвращаемое значение

mixed - Возвращает TRUE при удаче и PEAR_Error в обратном случае.

Заметка

Эта функция не должна вызываться статически.

Config_Container::Config_Container()

Config_Container::Config_Container() -- Constructor

Описание

Creates a new Config_Container and returns it by reference.

Параметр

string $type

Type of container object, should be something among 'section', 'comment', 'directive', 'blank'.

string $name

Name of container object. The name is required for sections and directives, not for blanks or comments.

string $content

Content of container object. The content is used in directives and comments.

array $attributes

Array of attributes for container object. Optionally, you can add attributes to your container. These can be used by the chosen parser.

Возвращаемое значение

object - A reference to the created object.

Заметка

Эта функция не должна вызываться статически.

Config_Container::addItem()

Config_Container::addItem() -- Add item to this item.

Описание

This method will add a Config_Container child to the current container children. Thus, addItem() can only be called one a section type container. If a position is specified, the object will be added at this position. If 'before' or 'after' are specified as position, a target object is required. The object will then be added before or after the target object position in the current container.

Параметр

object &$item

a container object

string $where

choose a position 'bottom', 'top', 'after', 'before'

object $target

needed if you choose 'before' or 'after' in $where. $target must be one of this container's children. ZendEngine2 will accept references with default. It will then be possible to have &$target instead.

Возвращаемое значение

object - A reference to the added object

Заметка

Эта функция не должна вызываться статически.

Config_Container::countChildren()

Config_Container::countChildren() -- Count children of container

Описание

This method will return the number of children this container has. If either $name or $type, it will affine its search just to return the number of children corresponding to these parameters.

Параметр

string $type

Type of children to count.

string $name

Name of children to count.

Возвращаемое значение

int - number of children found

Заметка

Эта функция не должна вызываться статически.

Config_Container::createBlank()

Config_Container::createBlank() -- Add blank line to item

Описание

The current item must be a section. This is a helper method that calls createItem()

Параметр

string $where

Where to create the new item ('top', 'bottom', 'before', 'after')

object $target

Required only if 'before' or 'after' is used for $where

Возвращаемое значение

object - reference to new item

Заметка

Эта функция не должна вызываться статически.

Config_Container::createComment()

Config_Container::createComment() -- Add comment to item

Описание

The current item must be a section. This is a helper method that calls createItem()

Параметр

string $content

Comment content

string $where

Where to create the new item ('top', 'bottom', 'before', 'after')

object $target

Required only if 'before' or 'after' is used for $where

Возвращаемое значение

object - reference to new item

Заметка

Эта функция не должна вызываться статически.

Config_Container::createDirective()

Config_Container::createDirective() -- Add directive to item

Описание

The current item must be a section. This is a helper method that calls createItem()

Параметр

string $name

Name of new directive

string $content

Content of new directive

mixed $attributes

Directive attributes

string $where

Where to create the new item ('top', 'bottom', 'before', 'after')

object $target

Required only if 'before' or 'after' is used for $where

Возвращаемое значение

object - reference to new item

Заметка

Эта функция не должна вызываться статически.

Config_Container::createItem()

Config_Container::createItem() -- Create new child for section item

Описание

This method must be called on a section, the created item can be anything. It adds a new child to the current item. If a position is specified, the child will be created at there. It is recommended to use the helper methods instead of calling this method directly.

Параметр

string $type

type of item: directive, section, comment, blank...

mixed $item

item name

string $content

item content

array $attributes

item attributes

string $where

choose a position 'bottom', 'top', 'after', 'before'

object $target

needed if you choose 'before' or 'after' for $where

Возвращаемое значение

object - reference to new item

Заметка

Эта функция не должна вызываться статически.

Config_Container::createSection()

Config_Container::createSection() -- Add section to item

Описание

Must be called on a section. This is a helper method that calls createItem()

Параметр

string $name

Name of new section

array array $attributes

Section attributes

string $where

Where to create the new item ('top', 'bottom', 'before', 'after')

object $target

Required only if 'before' or 'after' is used for $where

Возвращаемое значение

object - reference to new item

Заметка

Эта функция не должна вызываться статически.

Config_Container::getAttribute()

Config_Container::getAttribute() -- Get attribute value of item

Описание

This method returns the value associated with the key attribute. To get all attributes, see method getAttributes().

Параметр

string $attribute

Attribute key

Возвращаемое значение

mixed - item's attribute value

Заметка

Эта функция не должна вызываться статически.

Config_Container::getAttributes()

Config_Container::getAttributes() -- Get item attributes

Описание

This method returns an array containing the attributes of this container.

Возвращаемое значение

array - item's attributes

Заметка

Эта функция не должна вызываться статически.

Config_Container::getChild()

Config_Container::getChild() -- Return child object at specified index.

Описание

Children are stored in an array. This method returns the Config_Container object at the specified index.

Параметр

integer $index

Child index

Возвращаемое значение

mixed - returns reference to child object or FALSE if child does not exist

Заметка

Эта функция не должна вызываться статически.

Config_Container::getContent()

Config_Container::getContent() -- Get item content

Описание

Accessor method. Returns the item content.

Возвращаемое значение

mixed - item's content

Заметка

Эта функция не должна вызываться статически.

Config_Container::getItem()

Config_Container::getItem() -- Tries to find specific items

Описание

This method tries to find the items that respond to the specified parameters.

This method can only be called on an object of type 'section'. Note that root is a section. This method is not recursive and tries to keep the current structure.

Параметр

string $type

type of item: directive, section, comment, blank...

string $name

item name

mixed $content

find item with this content

array $attributes

find item with attribute set to the given value

integer $index

index of the item in the returned object list. If it is not set, will try to return the last item with this name.

Возвращаемое значение

mixed - reference to item found or FALSE when not found

Заметка

Эта функция не должна вызываться статически.

Config_Container::getItemIndex()

Config_Container::getItemIndex() -- Return item index in its parent children array

Описание

Children Config_Container objects are stored in an array. This method will return the index of this item in its parent array.

Возвращаемое значение

mixed - returns int or NULL if root object

Заметка

Эта функция не должна вызываться статически.

Config_Container::getItemPosition()

Config_Container::getItemPosition() -- Return item rank in its parent children array

Описание

Returns the item rank in its parent children array according to other items with same type and name.

Возвращаемое значение

mixed - returns int or NULL if root object

Заметка

Эта функция не должна вызываться статически.

Config_Container::getName()

Config_Container::getName() -- Get item name

Описание

Return the name of this item.

Возвращаемое значение

string - item's name

Заметка

Эта функция не должна вызываться статически.

Config_Container::getParent()

Config_Container::getParent() -- Return item parent object

Описание

Returns the item parent object.

Возвращаемое значение

object - reference to parent object or NULL if root object

Заметка

Эта функция не должна вызываться статически.

Config_Container::getType()

Config_Container::getType() -- Get item type

Описание

Gets this item's type.

Возвращаемое значение

string - item type

Заметка

Эта функция не должна вызываться статически.

Config_Container::isRoot()