PHP的PSR-0標準利用namespace來做autoloading

來源:互聯網
上載者:User

標籤:php   psr-0   namespace   autoloading   standard   

介紹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。

<?phpuse My\Full\Classname as Another, My\Full\NSname;$obj = new Another; // 執行個體化一個 My\Full\Classname 對象$obj = new \Another; // 執行個體化一個Another對象$obj = new Another\thing; // 執行個體化一個My\Full\Classname\thing對象$obj = new \Another\thing; // 執行個體化一個Another\thing對象$a = \strlen('hi'); // 調用全域函數strlen$b = \INI_ALL; // 訪問全域常量 INI_ALL$c = new \Exception('error'); // 執行個體化全域類 Exception?>

以上是namespace的簡要介紹,對此不瞭解的同學還是把細讀文檔吧。在眾多新的PHP項目中,namespace已經被普遍使用了。尤其是伴隨Composer的流行,它已經是很有必要去瞭解的特性了。


Autoloading(自動載入)

很多開發人員寫物件導向的應用程式時對每個類的定義建立一個 PHP 源檔案。一個很大的煩惱是不得不在每個指令碼開頭寫一個長長的包含(require, include)檔案清單(每個類一個檔案)。

而Autoloading,就是解決這個問題的,通過定義一個/系列autoload函數,它會在試圖使用尚未被定義的類時自動調用。通過調用autoload函數,指令碼引擎在 PHP 出錯失敗前有了最後一個機會載入所需的類。這個autoload函數可以是預設的__autoload(),如下:

<?phpfunction __autoload($class_name) {    require_once $class_name . '.php';}$obj  = new MyClass();
也可以採用更靈活的方式,通過spl_autoload_register()來定義我們自己的__autoload()函數:

<?phpfunction my_autoload($class_name) {require_once $class_name . '.php';}spl_autoload_register("my_autoload");$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
實現的範例

下面是一個按照如上標準進行自動載入的簡單範例:

<?phpfunction autoload($className){    //這裡的$className一般是用namespace的方式來引用的,文章開頭已有介紹    //去除$className左邊的'\' 這是PHP5.3的一個bug,詳見https://bugs.php.net/50731    $className = ltrim($className, '\\');    $fileName  = '';    $namespace = '';    //找到最後一個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 的實現下面有一個SplClassLoader 的實現範例,如果你遵循了如上的標準,可以用它來進行自動載入。這也是目前PHP5.3推薦的類載入標準。http://gist.github.com/221634
<?php /* * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * This software consists of voluntary contributions made by many individuals * and is licensed under the MIT license. For more information, see * <http://www.doctrine-project.org>. */ /** * SplClassLoader implementation that implements the technical interoperability * standards for PHP 5.3 namespaces and class names. * * http://groups.google.com/group/php-standards/web/psr-0-final-proposal?pli=1 * *     // Example which loads classes for the Doctrine Common package in the *     // Doctrine\Common namespace. *     $classLoader = new SplClassLoader('Doctrine\Common', '/path/to/doctrine'); *     $classLoader->register(); * * @license http://www.opensource.org/licenses/mit-license.html  MIT License * @author Jonathan H. Wage <[email protected]> * @author Roman S. Borschel <[email protected]> * @author Matthew Weier O'Phinney <[email protected]> * @author Kris Wallsmith <[email protected]> * @author Fabien Potencier <[email protected]> */class SplClassLoader{    private $_fileExtension = '.php';    private $_namespace;    private $_includePath;    private $_namespaceSeparator = '\\';     /**     * Creates a new <tt>SplClassLoader</tt> that loads classes of the     * specified namespace.     *      * @param string $ns The namespace to use.     */    public function __construct($ns = null, $includePath = null)    {        $this->_namespace = $ns;        $this->_includePath = $includePath;    }     /**     * Sets the namespace separator used by classes in the namespace of this class loader.     *      * @param string $sep The separator to use.     */    public function setNamespaceSeparator($sep)    {        $this->_namespaceSeparator = $sep;    }     /**     * Gets the namespace seperator used by classes in the namespace of this class loader.     *     * @return void     */    public function getNamespaceSeparator()    {        return $this->_namespaceSeparator;    }     /**     * Sets the base include path for all class files in the namespace of this class loader.     *      * @param string $includePath     */    public function setIncludePath($includePath)    {        $this->_includePath = $includePath;    }     /**     * Gets the base include path for all class files in the namespace of this class loader.     *     * @return string $includePath     */    public function getIncludePath()    {        return $this->_includePath;    }     /**     * Sets the file extension of class files in the namespace of this class loader.     *      * @param string $fileExtension     */    public function setFileExtension($fileExtension)    {        $this->_fileExtension = $fileExtension;    }     /**     * Gets the file extension of class files in the namespace of this class loader.     *     * @return string $fileExtension     */    public function getFileExtension()    {        return $this->_fileExtension;    }     /**     * Installs this class loader on the SPL autoload stack.     */    public function register()    {        spl_autoload_register(array($this, 'loadClass'));    }     /**     * Uninstalls this class loader from the SPL autoloader stack.     */    public function unregister()    {        spl_autoload_unregister(array($this, 'loadClass'));    }     /**     * Loads the given class or interface.     *     * @param string $className The name of the class to load.     * @return void     */    public function loadClass($className)    {        if (null === $this->_namespace || $this->_namespace.$this->_namespaceSeparator === substr($className, 0, strlen($this->_namespace.$this->_namespaceSeparator))) {            $fileName = '';            $namespace = '';            if (false !== ($lastNsPos = strripos($className, $this->_namespaceSeparator))) {                $namespace = substr($className, 0, $lastNsPos);                $className = substr($className, $lastNsPos + 1);                $fileName = str_replace($this->_namespaceSeparator, DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;            }            $fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . $this->_fileExtension;             require ($this->_includePath !== null ? $this->_includePath . DIRECTORY_SEPARATOR : '') . $fileName;        }    }}

完。


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.