PHP的PSR-0标准利用namespace来做autoloading

介绍PSR-0之前,先来说说命名空间(NameSpace)和Autoloading吧。

NameSpace(命名空间)

namespace是PHP5.3版本加入的新特性,用来解决在编写类库或应用程序时创建可重用的代码如类或函数时碰到的两类问题:

1.用户编写的代码与PHP内部的类/函数/常量或第三方类/函数/常量之间的名字冲突。
2.为很长的标识符名称(通常是为了缓解第一类问题而定义的)创建一个别名(或简短)的名称,提高源代码的可读性。

PHP 命名空间中的元素使用了类似文件系统的原理。例如,类名可以通过三种方式引用:
1.非限定名称,或不包含前缀的类名称,例如 $a=new foo(); 或 foo::staticmethod();。如果当前命名空间是 currentnamespace,foo 将被解析为 currentnamespace\foo。如果使用 foo 的代码是全局的,不包含在任何命名空间中的代码,则 foo 会被解析为foo。 警告:如果命名空间中的函数或常量未定义,则该非限定的函数名称或常量名称会被解析为全局函数名称或常量名称。详情参见 使用命名空间:后备全局函数名称/常量名称。
2.限定名称,或包含前缀的名称,例如 $a = new subnamespace\foo(); 或 subnamespace\foo::staticmethod();。如果当前的命名空间是 currentnamespace,则 foo 会被解析为 currentnamespace\subnamespace\foo。如果使用 foo 的代码是全局的,不包含在任何命名空间中的代码,foo 会被解析为subnamespace\foo。
3.完全限定名称,或包含了全局前缀操作符的名称,例如, $a = new \currentnamespace\foo(); 或 \currentnamespace\foo::staticmethod();。在这种情况下,foo 总是被解析为代码中的文字名(literal name)currentnamespace\foo。

另外注意访问任意全局类、函数或常量,都可以使用完全限定名称,例如 \strlen() 或 \Exception 或 \INI_ALL。

[php] view plain copy 在CODE上查看代码片派生到我的代码片
  1. <?php  
  2. use My\Full\Classname as Another, My\Full\NSname;  
  3.   
  4. $obj = new Another; // 实例化一个 My\Full\Classname 对象  
  5. $obj = new \Another; // 实例化一个Another对象  
  6. $obj = new Another\thing; // 实例化一个My\Full\Classname\thing对象  
  7. $obj = new \Another\thing; // 实例化一个Another\thing对象  
  8.   
  9. $a = \strlen('hi'); // 调用全局函数strlen  
  10. $b = \INI_ALL; // 访问全局常量 INI_ALL  
  11. $c = new \Exception('error'); // 实例化全局类 Exception  
  12. ?>  

以上是namespace的简要介绍,对此不了解的同学还是把细读文档吧。在众多新的PHP项目中,namespace已经被普遍使用了。尤其是伴随Composer的流行,它已经是很有必要去了解的特性了。


Autoload(自动加载)

很多开发者写面向对象的应用程序时对每个类的定义建立一个 PHP 源文件。一个很大的烦恼是不得不在每个脚本开头写一个长长的包含(require, include)文件列表(每个类一个文件)。

而Autoload,就是解决这个问题的,通过定义的一个或一系列autoload函数,它会在试图使用尚未被定义的类时自动调用。通过调用autoload函数,脚本引擎在 PHP 出错失败前有了最后一个机会加载所需的类。这个autoload函数可以是默认的__autoload(),如下:

[php] view plain copy 在CODE上查看代码片派生到我的代码片
  1. <?php  
  2. function __autoload($class_name) {  
  3.     require_once $class_name . '.php';  
  4. }  
  5.   
  6. $obj  = new MyClass();  
也可以采用更灵活的方式,通过spl_autoload_register()来定义我们自己的__autoload()函数:
[php] view plain copy 在CODE上查看代码片派生到我的代码片
  1. <?php  
  2. function my_autoload($class_name) {  
  3.     require_once $class_name . '.php';  
  4. }  
  5. spl_autoload_register("my_autoload");  
  6. $obj  = new MyClass();  
以上代码将my_autoload()函数注册到__autoload栈中,从而取到__autoload()函数(注意__autoload()函数将不再起作用,但可以显式的将其注册到__autoload栈)。注意到刚才提到了__autoload栈,意味着我们可以注册多个autoload函数,根据注册的顺序依次加载(通过spl_autoload_register的第三个参数可以改变这一顺序)。

在这里我们展示了autoload函数最简单的例子,当然通过一些规则的设置,也可以胜任实际环境中许多复杂的情况。

但是如果我们的项目依赖某些其他的项目,本来大家在各自独立的加载规则下能顺利运行,但融合在一起可能就不妙了。那么能否有一种通用的加载规则来解决这个问题?


PSR-0

PSR是由PHP Framework Interoperability Group(PHP通用性框架小组)发布的一系列标准/规范,目前包括了PSR-0~PSR-4共4个,而PSR-0就是其中的自动加载标准(其后的PSR-4称为改进的自动加载的标准,是PSR-0的补充。PSR-0使用更广泛)。https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md

下面描述了具体互操作性的自动加载所必须的条件:

强制要求

  • 一个完全合格的namespace和class必须符合这样的结构 \<Vendor Name><Namespace>*<Class Name>
  • 每个namespace必须有一个顶层的namespace("Vendor Name"提供者名字)
  • 每个namespace可以有多个子namespace
  • 当从文件系统中加载时,每个namespace的分隔符要转换成 DIRECTORY_SEPARATOR(操作系统路径分隔符)
  • 在CLASS NAME(类名)中,每个下划线(_)符号要转换成DIRECTORY_SEPARATOR。在namespace中,下划线(_)符号是没有(特殊)意义的。
  • 当从文件系统中载入时,合格的namespace和class一定是以 .php 结尾的
  • verdor name,namespaces,class名可以由大小写字母组合而成(大小写敏感的)
除此之外可能还会遵循这个规则:如果文件不存在则返回false。

例子

  • \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和Class Name中的下划线

  • \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
将下划线转换成DIRECTORY_SEPARATOR实际上是出于兼容PHP5.3之前的版本的考虑

实现的范例

下面是一个按照如上标准进行自动加载的简单范例:

[php] view plain copy 在CODE上查看代码片派生到我的代码片
  1. <?php  
  2. function autoload($className)  
  3. {  
  4.     //这里的$className一般是用namespace的方式来引用的,文章开头已有介绍  
  5.     //去除$className左边的'\' 这是PHP5.3的一个bug,详见https://bugs.php.net/50731  
  6.     $className = ltrim($className'\\');  
  7.     $fileName  = '';  
  8.     $namespace = '';  
  9.     //找到最后一个namespace分隔符的位置  
  10.     if ($lastNsPos = strrpos($className'\\')) {  
  11.         $namespace = substr($className, 0, $lastNsPos);  
  12.         $className = substr($className$lastNsPos + 1);  
  13.         $fileName  = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;  
  14.     }  
  15.     $fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';  
  16.   
  17.     require $fileName;  
  18. }  

SplClassLoader 的实现

下面有一个SplClassLoader 的实现范例,如果你遵循了如上的标准,可以用它来进行自动加载。这也是目前PHP5.3推荐的类加载标准。http://gist.github.com/221634
[php] view plain copy 在CODE上查看代码片派生到我的代码片
  1. <?php  
  2.    
  3. /* 
  4.  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
  5.  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
  6.  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 
  7.  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
  8.  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
  9.  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 
  10.  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 
  11.  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 
  12.  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
  13.  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 
  14.  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
  15.  * 
  16.  * This software consists of voluntary contributions made by many individuals 
  17.  * and is licensed under the MIT license. For more information, see 
  18.  * <http://www.doctrine-project.org>. 
  19.  */  
  20.    
  21. /** 
  22.  * SplClassLoader implementation that implements the technical interoperability 
  23.  * standards for PHP 5.3 namespaces and class names. 
  24.  * 
  25.  * http://groups.google.com/group/php-standards/web/psr-0-final-proposal?pli=1 
  26.  * 
  27.  *     // Example which loads classes for the Doctrine Common package in the 
  28.  *     // Doctrine\Common namespace. 
  29.  *     $classLoader = new SplClassLoader('Doctrine\Common', '/path/to/doctrine'); 
  30.  *     $classLoader->register(); 
  31.  * 
  32.  * @license http://www.opensource.org/licenses/mit-license.html  MIT License 
  33.  * @author Jonathan H. Wage <[email protected]> 
  34.  * @author Roman S. Borschel <[email protected]> 
  35.  * @author Matthew Weier O'Phinney <[email protected]> 
  36.  * @author Kris Wallsmith <[email protected]> 
  37.  * @author Fabien Potencier <[email protected]> 
  38.  */  
  39. class SplClassLoader  
  40. {  
  41.     private $_fileExtension = '.php';  
  42.     private $_namespace;  
  43.     private $_includePath;  
  44.     private $_namespaceSeparator = '\\';  
  45.    
  46.     /** 
  47.      * Creates a new <tt>SplClassLoader</tt> that loads classes of the 
  48.      * specified namespace. 
  49.      *  
  50.      * @param string $ns The namespace to use. 
  51.      */  
  52.     public function __construct($ns = null, $includePath = null)  
  53.     {  
  54.         $this->_namespace = $ns;  
  55.         $this->_includePath = $includePath;  
  56.     }  
  57.    
  58.     /** 
  59.      * Sets the namespace separator used by classes in the namespace of this class loader. 
  60.      *  
  61.      * @param string $sep The separator to use. 
  62.      */  
  63.     public function setNamespaceSeparator($sep)  
  64.     {  
  65.         $this->_namespaceSeparator = $sep;  
  66.     }  
  67.    
  68.     /** 
  69.      * Gets the namespace seperator used by classes in the namespace of this class loader. 
  70.      * 
  71.      * @return void 
  72.      */  
  73.     public function getNamespaceSeparator()  
  74.     {  
  75.         return $this->_namespaceSeparator;  
  76.     }  
  77.    
  78.     /** 
  79.      * Sets the base include path for all class files in the namespace of this class loader. 
  80.      *  
  81.      * @param string $includePath 
  82.      */  
  83.     public function setIncludePath($includePath)  
  84.     {  
  85.         $this->_includePath = $includePath;  
  86.     }  
  87.    
  88.     /** 
  89.      * Gets the base include path for all class files in the namespace of this class loader. 
  90.      * 
  91.      * @return string $includePath 
  92.      */  
  93.     public function getIncludePath()  
  94.     {  
  95.         return $this->_includePath;  
  96.     }  
  97.    
  98.     /** 
  99.      * Sets the file extension of class files in the namespace of this class loader. 
  100.      *  
  101.      * @param string $fileExtension 
  102.      */  
  103.     public function setFileExtension($fileExtension)  
  104.     {  
  105.         $this->_fileExtension = $fileExtension;  
  106.     }  
  107.    
  108.     /** 
  109.      * Gets the file extension of class files in the namespace of this class loader. 
  110.      * 
  111.      * @return string $fileExtension 
  112.      */  
  113.     public function getFileExtension()  
  114.     {  
  115.         return $this->_fileExtension;  
  116.     }  
  117.    
  118.     /** 
  119.      * Installs this class loader on the SPL autoload stack. 
  120.      */  
  121.     public function register()  
  122.     {  
  123.         spl_autoload_register(array($this'loadClass'));  
  124.     }  
  125.    
  126.     /** 
  127.      * Uninstalls this class loader from the SPL autoloader stack. 
  128.      */  
  129.     public function unregister()  
  130.     {  
  131.         spl_autoload_unregister(array($this'loadClass'));  
  132.     }  
  133.    
  134.     /** 
  135.      * Loads the given class or interface. 
  136.      * 
  137.      * @param string $className The name of the class to load. 
  138.      * @return void 
  139.      */  
  140.     public function loadClass($className)  
  141.     {  
  142.         if (null === $this->_namespace || $this->_namespace.$this->_namespaceSeparator === substr($className, 0, strlen($this->_namespace.$this->_namespaceSeparator))) {  
  143.             $fileName = '';  
  144.             $namespace = '';  
  145.             if (false !== ($lastNsPos = strripos($className$this->_namespaceSeparator))) {  
  146.                 $namespace = substr($className, 0, $lastNsPos);  
  147.                 $className = substr($className$lastNsPos + 1);  
  148.                 $fileName = str_replace($this->_namespaceSeparator, DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;  
  149.             }  
  150.             $fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . $this->_fileExtension;  
  151.    
  152.             require ($this->_includePath !== null ? $this->_includePath . DIRECTORY_SEPARATOR : '') . $fileName;  
  153.         }  
  154.     }  
  155. }  

看到这里你可能还有疑问,比如psr-0中给出的例子

\Symfony\Core\Request => /path/to/project/lib/vendor/Symfony/Core/Request.php

在=>号之前是我们要去加载的类,而后面的部分是这个文件在文件系统中的路径(我们实际加载的是这个)。在加载Symfony\Core\Request时,并没有同时给出实际路径来,那么是如何得到这个映射的呢?在PSR-0标准中并没有对/path/to/project/lib路径的强制要求,而是可以有自己的实现。一般有两种方式,一种就是使用php配置中的include_path(上面给出的例子有使用这个方式来做),第二种就是自己去注册这种映射,可以选用其中一种,或者两种都兼容。下面就来看看在Symfony中是怎么做的?

[php] view plain copy 在CODE上查看代码片派生到我的代码片
  1. <?php  
  2. require_once '/path/to/src/Symfony/Component/ClassLoader/ClassLoader.php';  
  3.   
  4. use Symfony\Component\ClassLoader\ClassLoader;  
  5.   
  6. $loader = new ClassLoader();  
  7.   
  8. // to enable searching the include path (eg. for PEAR packages)  
  9. $loader->setUseIncludePath(true);  
  10.   
  11. // ... register namespaces and prefixes here - see below  
  12.   
  13. $loader->register();  
  14.   
  15. // register a single namespaces  
  16. $loader->addPrefix('Symfony', __DIR__.'/vendor/symfony/symfony/src');  
此时就将 Symfony 这个namespace 注册到了一个真实的路径上,Symfony的子命名空间也可以使用这个路径了。

完。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章