1. psr-4规范:自动加载
虽然在[psr-4-meta]中指出psr-4是对psr-0规范的补充而不是替换,但是在[psr-0]中已经写到psr-0于2014.10.21被废弃,并在[psr-4-meta]中详细写明了psr-0的不足,已经不能满足面向package的自动加载。
psr-4规范能够满足面向package的自动加载,它规范了如何从文件路径自动加载类,同时规范了自动加载文件的位置。
1.1 概述
这份psr规范描述了从文件路径自动加载类。可以与psr-0规范互操作,可以一起使用。这份psr也描述了自动加载的文件应当放在哪里。
1.2 规范
1.2.1 术语class是指classes, interfaces, traits, 以及其他类似的结构.
1.2.2 一个完全合乎规格的类名(a fully qualified class name)格式如下:
\(\)*\
(1) 完全合规的类名必须(must)有一个顶级命名空间名称,也就是通常所说的vendor命名空间.
(2) 完全合规的类名可以(may)有一个或多个二级命名空间名称(sub-namespace names).
(3) 完全合规的类名必须(must)以类名来结尾。
(4) 在完全合规的类名的任意一个部分,下划线都没有特殊的含义。
(5) 在完全合规的类名中,可以(may)是任意大小写字母混合。
(6) 所有的类名必须(must)按大小写敏感方式来引用。
1.2.3 当加载完全合规的类名对应的文件时...
(1) 在完全合规的类名中, 不包含前面的命名空间分隔符,由一个顶级命名空间与一个或多个二级命名空间名称组成的命名空间前缀,对应于至少一个“base目录”.
(2) 在命名空间前缀后面的二级命名空间名称对应于“base目录”中的一个子目录, 这里命名空间分隔符表示目录分隔符。子目录名称必须(must)匹配到二级命名空间名称。
(3) 后面的类名对应于以.php为后缀的文件名,这个文件名必须(must)匹配到后面的类名。
(4) 自动加载实现一定不能(must not)抛出异常,一定不能(must not)引发任何级别的错误, 并且不应当(should not)返回值。
1.3. 举例 下面的表展示了对一个完全合规的类名, 命名空间前缀以及base目录对应的文件路径.
完全合规类名 命名空间前缀 base目录 最终的文件路径
\acme\log\writer\file_writer acme\log\writer ./acme-log-writer/lib/ ./acme-log-writer/lib/file_writer.php
\aura\web\response\status aura\web /path/to/aura-web/src/ /path/to/aura-web/src/response/status.php
\symfony\core\request symfony\core ./vendor/symfony/core/ ./vendor/symfony/core/request.php
\zend\acl zend /usr/includes/zend/ /usr/includes/zend/acl.php
备注:以第一行为例来说明,完全合规的类名是“\acme\log\writer\file_writer”, 去掉前面的命名空间分隔符'\', 则命名空间前缀为acme\log\writer, 类名为file_writer。这个命名空间前缀对应的base目录为./acme-log-writer/lib/, 因此最终加载的文件名为:base目录+类名+.php, 即./acme-log-writer/lib/file_writer.php
遵循本规范的自动加载器的实现举例, 可参见下面的代码样例。这些实现样例一定不能(must not)被视为本规范的内容,它们可能(may)随时发生改变。
2. 代码样例 以下代码展示了遵循psr-4的类定义,
闭包(closure)举例:
addnamespace('foo\bar', '/path/to/packages/foo-bar/tests'); * * the following line would cause the autoloader to attempt to load the * \foo\bar\qux\quux class from /path/to/packages/foo-bar/src/qux/quux.php: * 下面代码将用/path/to/packages/foo-bar/src/qux/quux.php文件来加载\foo\bar\qux\quux类。 * * prefixes[$prefix] = array(); } // retain the base directory for the namespace prefix // 绑定命名空间前缀对应的base目录 if ($prepend) { array_unshift($this->prefixes[$prefix], $base_dir); } else { array_push($this->prefixes[$prefix], $base_dir); } } /** * loads the class file for a given class name. * 根据类名来加载类文件。 * * @param string $class the fully-qualified class name. * @return mixed the mapped file name on success, or boolean false on * failure. */ public function loadclass($class) { // the current namespace prefix $prefix = $class; // work backwards through the namespace names of the fully-qualified // class name to find a mapped file name // 从后面开始遍历完全合格类名中的命名空间名称, 来查找映射的文件名 while (false !== $pos = strrpos($prefix, '\\')) { // retain the trailing namespace separator in the prefix // 保留命名空间前缀中尾部的分隔符 $prefix = substr($class, 0, $pos + 1); // the rest is the relative class name // 剩余的就是相对类名称 $relative_class = substr($class, $pos + 1); // try to load a mapped file for the prefix and relative class // 利用命名空间前缀和相对类名来加载映射文件 $mapped_file = $this->loadmappedfile($prefix, $relative_class); if ($mapped_file) { return $mapped_file; } // remove the trailing namespace separator for the next iteration // of strrpos() // 删除命名空间前缀尾部的分隔符,以便用于下一次strrpos()迭代 $prefix = rtrim($prefix, '\\'); } // never found a mapped file // 未找到映射文件 return false; } /** * load the mapped file for a namespace prefix and relative class. * 根据命名空间前缀和相对类来加载映射文件 * * @param string $prefix the namespace prefix. * @param string $relative_class the relative class name. * @return mixed boolean false if no mapped file can be loaded, or the * name of the mapped file that was loaded. */ protected function loadmappedfile($prefix, $relative_class) { // are there any base directories for this namespace prefix? // 命名空间前缀中有base目录吗? if (isset($this->prefixes[$prefix]) === false) { return false; } // look through base directories for this namespace prefix // 遍历命名空间前缀的base目录 foreach ($this->prefixes[$prefix] as $base_dir) { // replace the namespace prefix with the base directory, // replace namespace separators with directory separators // in the relative class name, append with .php // 用base目录替代命名空间前缀, // 在相对类名中用目录分隔符'/'来替换命名空间分隔符'\', // 并在后面追加.php组成$file的绝对路径 $file = $base_dir . str_replace('\\', '/', $relative_class) . '.php'; // if the mapped file exists, require it // 若映射文件存在,则require该文件 if ($this->requirefile($file)) { // yes, we're done return $file; } } // never found it return false; } /** * if a file exists, require it from the file system. * * @param string $file the file to require. * @return bool true if the file exists, false if not. */ protected function requirefile($file) { if (file_exists($file)) { require $file; return true; } return false; }}
3. 单元测试 下面是对应的单元测试代码:
files = $files; } protected function requirefile($file) { return in_array($file, $this->files); }}class psr4autoloaderclasstest extends \phpunit_framework_testcase{ protected $loader; protected function setup() { $this->loader = new mockpsr4autoloaderclass; $this->loader->setfiles(array( '/vendor/foo.bar/src/classname.php', '/vendor/foo.bar/src/doomclassname.php', '/vendor/foo.bar/tests/classnametest.php', '/vendor/foo.bardoom/src/classname.php', '/vendor/foo.bar.baz.dib/src/classname.php', '/vendor/foo.bar.baz.dib.zim.gir/src/classname.php', )); $this->loader->addnamespace( 'foo\bar', '/vendor/foo.bar/src' ); $this->loader->addnamespace( 'foo\bar', '/vendor/foo.bar/tests' ); $this->loader->addnamespace( 'foo\bardoom', '/vendor/foo.bardoom/src' ); $this->loader->addnamespace( 'foo\bar\baz\dib', '/vendor/foo.bar.baz.dib/src' ); $this->loader->addnamespace( 'foo\bar\baz\dib\zim\gir', '/vendor/foo.bar.baz.dib.zim.gir/src' ); } public function testexistingfile() { $actual = $this->loader->loadclass('foo\bar\classname'); $expect = '/vendor/foo.bar/src/classname.php'; $this->assertsame($expect, $actual); $actual = $this->loader->loadclass('foo\bar\classnametest'); $expect = '/vendor/foo.bar/tests/classnametest.php'; $this->assertsame($expect, $actual); } public function testmissingfile() { $actual = $this->loader->loadclass('no_vendor\no_package\noclass'); $this->assertfalse($actual); } public function testdeepfile() { $actual = $this->loader->loadclass('foo\bar\baz\dib\zim\gir\classname'); $expect = '/vendor/foo.bar.baz.dib.zim.gir/src/classname.php'; $this->assertsame($expect, $actual); } public function testconfusion() { $actual = $this->loader->loadclass('foo\bar\doomclassname'); $expect = '/vendor/foo.bar/src/doomclassname.php'; $this->assertsame($expect, $actual); $actual = $this->loader->loadclass('foo\bardoom\classname'); $expect = '/vendor/foo.bardoom/src/classname.php'; $this->assertsame($expect, $actual); }}
4. psr-4应用
php的包管理系统composer已经支持psr-4,同时也允许在composer.json中定义不同的prefix使用不同的自动加载机制。
composer使用psr-0风格
vendor/ vendor_name/ package_name/ src/ vendor_name/ package_name/ classname.php # vendor_name\package_name\classname tests/ vendor_name/ package_name/ classnametest.php # vendor_name\package_name\classname
composer使用psr-4风格
vendor/ vendor_name/ package_name/ src/ classname.php # vendor_name\package_name\classname tests/ classnametest.php # vendor_name\package_name\classnametest
对比以上两种结构,明显可以看出psr-4带来更简洁的文件结构。
5. 参考资料
[php-fig] php-fig, http://www.php-fig.org/
[psr-0] autoloading standard, http://www.php-fig.org/psr/psr-0/
[psr-4] autoloader, http://www.php-fig.org/psr/psr-4/
[psr-4-meta] psr-4 meta document, http://www.php-fig.org/psr/psr-4/meta/
[psr-4-example] example implementations of psr-4, http://www.php-fig.org/psr/psr-4/examples/