PSR-0 : PHP autoload 规范 (中文翻译)(转)
强制约定
- 一个合格的名空间-类应当遵循这样的结构 \<Vendor Name>\(<Namespace>\)*<Class Name>
A fully-qualified namespace and class must have the following structure \<Vendor Name>\(<Namespace>\)*<Class Name>
- 每个名空间需要有一个顶级名空间 (“Vendor Name”)(提供者名称).
Each namespace must have a top-level namespace (“Vendor Name”).
- 每个名空间可以有任意多个子名空间
Each namespace can have as many sub-namespaces as it wishes.
- 从文件系统载入时,每个名空间分隔符将被转换为一个路径分隔符
Each namespace separator is converted to a DIRECTORY_SEPARATOR when loading from the file system.
- 类名中的每个下划线符( _ )将被转化为一个路径分隔符,名空间中的下划线符( _ )没有任何特定含义
Each _ character in the CLASS NAME is converted to a DIRECTORY_SEPARATOR. The _ character has no special meaning in the namespace.
- 一个合格的名空间-类所对应加载的文件必须是以.php结尾的
The fully-qualified namespace and class is suffixed with .php when loading from the file system.
- Vendor Name(提供者名称)、名空间、类名中的字符可以是大小写的任意组合
Alphabetic characters in vendor names, namespaces, and class names may be of any combination of lower case and upper case.
范例
\Doctrine\Common\IsolatedClassLoader
=>/path/to/project/lib/vendor/Doctrine/Common/IsolatedClassLoader.php
\Symfony\Core\Request
=>/path/to/project/lib/vendor/Symfony/Core/Request.php
\Zend\Acl
=>/path/to/project/lib/vendor/Zend/Acl.php
\Zend\Mail\Message
=>/path/to/project/lib/vendor/Zend/Mail/Message.php
名空间与类名中的下划线
\namespace\package\Class_Name
=>/path/to/project/lib/vendor/namespace/package/Class/Name.php
\namespace\package_name\Class_Name
=>/path/to/project/lib/vendor/namespace/package_name/Class/Name.php
我们指定的标准应当成为保证autoload机制互通性的最小化规范。
你可以利用这个示例SplClassLoader加载PHP5.3的类来测试自己是否遵循了本规范
The standards we set here should be the lowest common denominator for painless autoloader interoperability. You can test that you are following these standards by utilizing this sample SplClassLoader implementation which is able to load PHP 5.3 classes.
实例实现
以下是一个实现上述规范的autoload函数简单示例
Below is an example function to simply demonstrate how the above proposed standards are autoloaded.
<?php function autoload($className) { $className=ltrim($className,'\\'); $fileName =''; $namespace=''; if($lastNsPos=strrpos($className,'\\')){ $namespace=substr($className,0,$lastNsPos); $className=substr($className,$lastNsPos+1); $fileName =str_replace('\\',DIRECTORY_SEPARATOR,$namespace).DIRECTORY_SEPARATOR; } $fileName.=str_replace('_',DIRECTORY_SEPARATOR,$className).'.php'; require$fileName; }
SplClassLoader实现
以下gist是一个SplClassLoader实现范例,如果你遵循这套规范,我们推荐你使用它来加载你的php5.3类
The following gist is a sample SplClassLoader implementation that can load your classes if you follow the autoloader interoperability standards proposed above. It is the current recommended way to load PHP 5.3 classes that follow these standards.