- Rules
- Requirement
- use of include/require/require_once/include_once not allowed
- Requirement
- Directory structure
- Requirement
- Class-to-file convention
- Requirement
- Base Exception class
- Requirement
- Data files
- Requirement
- Loading other classes
- Requirement
- Including Code
- User Notes:
- Rules
- Requirement
- use of include/require/require_once/include_once not allowed
- Requirement
- Directory structure
- Requirement
- Class-to-file convention
- Requirement
- Base Exception class
- Requirement
- Data files
- Requirement
- Loading other classes
- Requirement
- User Notes:
- Установка модулей PEAR
- Использование PEAR с PHP 7.0 и новее
- Предварительная настройка
- Установка модулей
- Указание пути до папки c модулями в include_path
- Использование PEAR с PHP 5.6
- Предварительная настройка
- Установка модулей
- Указание пути до папки с модулями в include_path
Rules
All classes and functions must have a namespace of at the minimum PEAR2. An example:
Classes may use longer namespaces, for instance an HTTP_Request class may instead choose to use this declarative syntax:
As such, underscores are no longer required of any classes if there is a namespace. Class PEAR2_HTTP_Request instead becomes PEAR2\HTTP\Request. Package names, however, will use underscores, making PEAR2_HTTP_Request the package name.
Requirement
No Exceptions to this rule
use of include/require/require_once/include_once not allowed
include/require/require_once/include_once is not allowed for loading class files. Users will be expected to load files either with __autoload() or a customized solution for more advanced users. Instead, classes should simply be used. import with a comment describing the class’s location must be used to document all internal dependencies (as written below). Instead of:
this class should simply be used:
This allows packages to work without modification no matter how they are structured on-disk, including running out of a single large file, inside a phar archive, and provides much-needed flexibility.
Requirement
No Exceptions to this rule
Directory structure
Follows the directory structure in the PEAR2 Subversion repository:
Note that all package.xml files must specify a baseinstalldir of «/» for the src/ directory:
Requirement
Exceptions may be made to this rule with approval from the PEAR Group
Class-to-file convention
All public classes must be in their own file with underscores (_) or namespace separators (\) replaced by directory separator, so that PEAR2_PackageName_Base class or PEAR2\PackageName\Base class is always located in PEAR2/PackageName/Base.php (this is required to make autoload work)
Requirement
Exceptions may be made to this rule only with explicit approval from the PEAR Group via a public vote
Base Exception class
PEAR2\Exception is used as base class for all exception classes. Each package must define a base class that is packagename_Exception. For example, the PEAR2\PackageName class defines an exception as follows in PEAR2/PackageName/Exception.php:
‘PEAR2\Exception will be its own package’
Requirement
No Exceptions to this rule
Data files
package.xml replacement tasks should not be used to retrieve path locations for php, data, or www files. Replacements are still allowed in doc and test files.
The installation structure of a package has implicit php_dir/src installation location, and data files are always located in php_dir/data/channel/PackageName/. To retrieve a data file within PEAR2/PackageName/Subfile.php, you could use code like this example
.
// retrieve data from info.txt
$info = file_get_contents ( dirname ( __FILE__ ) .
‘../../../data/pear2.php.net/PEAR2_PackageName/info.txt’ );
?>?php
Requirement
No Exceptions to this rule
Loading other classes
Inside optional component loading methods (like factory or driver loading, etc.) class_exists($classname, true) should be used where a «class not found» fatal error would be confusing. For example, when loading a driver, a graceful exit via exception with helpful error message is preferrable to the fatal error:
if (! class_exists ( «PEAR2_PackageName_Driver_ $class » , true )) throw new PEAR2 \ PackageName \ Exception ( ‘Unknown driver ‘ .
$class . ‘, be sure the driver exists and is loaded
prior to use’ );
>
?>?php
Requirement
This rule is optional and is a suggested coding practice
Including Code
Anywhere you are unconditionally including a class file, use require_once. Anywhere you are conditionally including a class file (for example, factory methods), use include_once. Either of these will ensure that class files are included only once. They share the same file list, so you don’t need to worry about mixing them — a file included with require_once will not be included again by include_once.
include_once and require_once are statements, not functions. Parentheses should not surround the subject filename.
User Notes:
I think that since SPL is part of PHP for a long time now, no includes should be used at all anymore. Namespaces have much more advantages. They automatically include files and they do this only when it is required (so memory is saved — especially if you use frameworks). They also define the folder structure (which is an advantage imho, not a disadvantage) so you don’t have to care how much folders you have to go down or up and the namespaces prevent name collisions. Also you can specify the file extension(s) through the SPL at one place, instead writing them in every include statement (imagine your hoster is a cool badass and is using PHP 7 on the server but your PHP application needs to run under PHP 5 so you have to use .php5 file extensions — have a nice day changing your code. ).
To change all require_once(‘foo.php’); to require_once ‘foo.php’ execute this:
find . -name ‘*.php’ -print | xargs egrep -l \
‘require_once\s*(\(.*\));’\ | xargs sed -i.sedorig -e \
‘s/require_once\s*(\(.*\));/require_once \1;/’
(thanks to Robert Hajime Lanning for that)
Then to remove all the «.php.sedorig» backup files execute this:
find . -name «*.php.sedorig» -type f -exec rm -rf <> \;
Rules
All classes and functions must have a namespace of at the minimum PEAR2. An example:
Classes may use longer namespaces, for instance an HTTP_Request class may instead choose to use this declarative syntax:
As such, underscores are no longer required of any classes if there is a namespace. Class PEAR2_HTTP_Request instead becomes PEAR2\HTTP\Request. Package names, however, will use underscores, making PEAR2_HTTP_Request the package name.
Requirement
No Exceptions to this rule
use of include/require/require_once/include_once not allowed
include/require/require_once/include_once is not allowed for loading class files. Users will be expected to load files either with __autoload() or a customized solution for more advanced users. Instead, classes should simply be used. import with a comment describing the class’s location must be used to document all internal dependencies (as written below). Instead of:
this class should simply be used:
This allows packages to work without modification no matter how they are structured on-disk, including running out of a single large file, inside a phar archive, and provides much-needed flexibility.
Requirement
No Exceptions to this rule
Directory structure
Follows the directory structure in the PEAR2 Subversion repository:
Note that all package.xml files must specify a baseinstalldir of «/» for the src/ directory:
Requirement
Exceptions may be made to this rule with approval from the PEAR Group
Class-to-file convention
All public classes must be in their own file with underscores (_) or namespace separators (\) replaced by directory separator, so that PEAR2_PackageName_Base class or PEAR2\PackageName\Base class is always located in PEAR2/PackageName/Base.php (this is required to make autoload work)
Requirement
Exceptions may be made to this rule only with explicit approval from the PEAR Group via a public vote
Base Exception class
PEAR2\Exception is used as base class for all exception classes. Each package must define a base class that is packagename_Exception. For example, the PEAR2\PackageName class defines an exception as follows in PEAR2/PackageName/Exception.php :
‘PEAR2\Exception will be its own package’
Requirement
No Exceptions to this rule
Data files
package.xml replacement tasks should not be used to retrieve path locations for php, data, or www files. Replacements are still allowed in doc and test files.
The installation structure of a package has implicit php_dir/src installation location, and data files are always located in php_dir/data/channel/PackageName/ . To retrieve a data file within PEAR2/PackageName/Subfile.php , you could use code like this example
.
// retrieve data from info.txt
$info = file_get_contents ( dirname ( __FILE__ ) .
‘../../../data/pear2.php.net/PEAR2_PackageName/info.txt’ );
?>?php
Requirement
No Exceptions to this rule
Loading other classes
Inside optional component loading methods (like factory or driver loading, etc.) class_exists ($classname, true) should be used where a «class not found» fatal error would be confusing. For example, when loading a driver, a graceful exit via exception with helpful error message is preferrable to the fatal error:
if (! class_exists ( «PEAR2_PackageName_Driver_ $class » , true )) throw new PEAR2 \ PackageName \ Exception ( ‘Unknown driver ‘ .
$class . ‘, be sure the driver exists and is loaded
prior to use’ );
>
?>?php
Requirement
This rule is optional and is a suggested coding practice
User Notes:
Well, the PEAR2 «root» namespace seems to be superfluous. Especially for large packages that contain more than one level of nested directories/namespaces.
Beside the overhead one has to type, this also looks very awkward. And in previous versions of PHP and PEAR coding standards no-one was forced to use a «PEAR_» prefix either.
I understand that this might be necessary in order to use some universal PEAR2\Autoloader that does not affect other namespaces, but a (maybe static) method like PEAR2\Autoloader::registerNamespace($prefix) should also do the trick. Or simply leave it to the package maintainer to implement autoloading in «extern» namespaces.
Last but not least; neither CPAN, PyPI nor any of the other popular networks have ever introduced such a rule. I’m pretty sure they know why.
Установка модулей PEAR
PEAR — это репозиторий классов (модулей) языка PHP, список доступных модулей можно увидеть на её официальном сайте — https://pear.php.net/packages.php. Установка модулей из данного репозитория на виртуальном хостинге возможна через официальную утилиту командной строки pear.
На серверах виртуального хостинга по умолчанию доступна команда pear, но она работает только для версий PHP 5.2-5.6 включительно. Для установки модулей на PHP 7.0 и новее необходимо установить последнюю версию утилиты на аккаунт по инструкции ниже. Одновременная работа системной утилиты pear и утилиты, установленной локально, в рамках одного аккаунта не гарантируется.
Использование PEAR с PHP 7.0 и новее
Предварительная настройка
Перед установкой первого модуля предварительно необходимо установить последнюю версию утилиты pear, используя официальный установщик в консоли SSH в домашней директории:
На первом шаге можно выбрать все параметры по умолчанию, на втором на вопрос «Would you like to alter php.ini ? [Y/n]» необходимо ввести символ «n» (нет). На третьем шаге нужно подтвердить установку клавишей Enter.
3. Добавить путь к утилите в переменную $PATH, чтобы был доступен её запуск из любой папки на аккаунте
Добавьте в файл .profile в корне аккаунта строку вида:
Если файла .profile в корне аккаунта нет, его необходимо предварительно создать.
4. Выйти из SSH-сессии и войти заново для применения изменений в $PATH
5. Обновить данные репозитория
Установка модулей
Установка производится командой вида pear install -o . К примеру, установка пакета mail:
$ pear install -o mail Did not download optional dependencies: pear/Net_SMTP, use --alldeps to download automatically pear/Mail can optionally use package "pear/Net_SMTP" (version >= 1.10.0) downloading Mail-1.5.0.tgz . Starting to download Mail-1.5.0.tgz (23,221 bytes) . done: 23,221 bytes install ok: channel://pear.php.net/Mail-1.5.0
Указание пути до папки c модулями в include_path
Самым последним действием нужно указать сайту путь до директории, в которой хранятся классы PEAR. Для этого достаточно добавить в файл .htaccess одну строку вида:
в которую необходимо подставить данные в соответствии с вашим аккаунтом. Например, для логина testlogin директива будет выглядеть так:
Как альтернативный вариант, можно добавить указание пути к папке в начало PHP-скрипта, такой строкой:
Использование PEAR с PHP 5.6
Предварительная настройка
Перед установкой первого модуля предварительно необходимо создать файл с настройками в домашней директории такой командой по SSH (выполняется также из домашней директории):
Затем следует скопировать стандартные файлы PEAR, чтобы копия хранилась в домашнем каталоге:
Установка модулей
Установка производится командой вида PHP_PEAR_PHP_BIN=php5.6 pear install -o . К примеру, установка пакета File_Find:
$ PHP_PEAR_PHP_BIN=php5.6 pear install -o File_Find downloading File_Find-1.3.3.tgz . Starting to download File_Find-1.3.3.tgz (8,212 bytes) . done: 8,212 bytes install ok: channel://pear.php.net/File_Find-1.3.3
Указание пути до папки с модулями в include_path
Самым последним действием нужно указать сайту путь до директории, в которой хранятся классы PEAR. Для этого достаточно добавить в файл .htaccess одну строку вида:
в которую необходимо подставить данные в соответствии с вашим аккаунтом. Например, для логина testlogin директива будет выглядеть так:
Как альтернативный вариант, можно добавить указание пути к папке в начало PHP-скрипта, такой строкой: