FIG-PHP PSR規範系列4-自動加載

1.  PSR-4規範:自動加載

    雖然在[PSR-4-Meta]中指出PSR-4是對PSR-0規範的補充而不是替換,可是在[PSR-0]中已經寫到PSR-0於2014.10.21被廢棄,並在[PSR-4-Meta]中詳細寫明瞭PSR-0的不足,已經不能知足面向package的自動加載。 php

    PSR-4規範可以知足面向package的自動加載,它規範瞭如何從文件路徑自動加載類,同時規範了自動加載文件的位置。web

1.1 概述

    這份PSR規範描述了從文件路徑自動加載類。能夠與PSR-0規範互操做,能夠一塊兒使用。這份PSR也描述了自動加載的文件應當放在哪裏。 shell

1.2 規範

1.2.1 術語"class"是指classes, interfaces, traits, 以及其餘相似的結構.json

1.2.2 一個徹底合乎規格的類名(A fully qualified class name)格式以下:
segmentfault

        \<NamespaceName>(\<SubNamespaceNames>)*\<ClassName>
數組

        (1) 徹底合規的類名必須(MUST)有一個頂級命名空間名稱,也就是一般所說的"vendor命名空間".閉包

        (2) 徹底合規的類名能夠(MAY)有一個或多個二級命名空間名稱(sub-namespace names).app

       (3) 徹底合規的類名必須(MUST)以類名來結尾。composer

       (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)舉例:

<?php
/**
 * An example of a project-specific implementation.
 * 
 * After registering this autoload function with SPL, the following line
 * would cause the function to attempt to load the \Foo\Bar\Baz\Qux class
 * from /path/to/project/src/Baz/Qux.php:
 * 
 *      new \Foo\Bar\Baz\Qux;
 *      
 * @param string $class The fully-qualified class name.
 * @return void
 */
spl_autoload_register(function ($class) {

    // project-specific namespace prefix
    // 項目的命名空間前綴
    $prefix = 'Foo\\Bar\\';

    // base directory for the namespace prefix
    // 命名空間前綴對應的base目錄
    $base_dir = __DIR__ . '/src/';

    // does the class use the namespace prefix?
    // 檢查$class中是否包含命名空間前綴
    $len = strlen($prefix);
    if (strncmp($prefix, $class, $len) !== 0) {
        // no, move to the next registered autoloader
        // 未包含,當即返回
        return;
    }

    // get the relative class name
    // 獲取相對類名
    $relative_class = substr($class, $len);

    // 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 file exists, require it
    // 若是文件存在,則經過require關鍵字包含文件
    if (file_exists($file)) {
        require $file;
    }
});

下面這個類處理多個命名空間:

<?php
namespace Example;

/**
 * An example of a general-purpose implementation that includes the optional
 * functionality of allowing multiple base directories for a single namespace
 * prefix.
 * 下面例子中在一個命名空間前綴下有多個base目錄。
 * 
 * Given a foo-bar package of classes in the file system at the following
 * paths ...
 * 在下面路徑中foo-bar包中存在如下類:
 * 
 *     /path/to/packages/foo-bar/
 *         src/
 *             Baz.php             # Foo\Bar\Baz
 *             Qux/
 *                 Quux.php        # Foo\Bar\Qux\Quux
 *         tests/
 *             BazTest.php         # Foo\Bar\BazTest
 *             Qux/
 *                 QuuxTest.php    # Foo\Bar\Qux\QuuxTest
 * 
 * ... add the path to the class files for the \Foo\Bar\ namespace prefix
 * as follows:
 * ...對\Foo\Bar\命名空間前綴,添加類文件的路徑
 * 
 *      <?php
 *      // instantiate the loader
 *      // 初始化loader 
 *      $loader = new \Example\Psr4AutoloaderClass;
 *      
 *      // register the autoloader
 *      // 註冊autoloader
 *      $loader->register();
 *      
 *      // register the base directories for the namespace prefix
 *      // 註冊命名空間前綴的多個base目錄
 *      $loader->addNamespace('Foo\Bar', '/path/to/packages/foo-bar/src');
 *      $loader->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類。
 * 
 *      <?php
 *      new \Foo\Bar\Qux\Quux;
 * 
 * The following line would cause the autoloader to attempt to load the 
 * \Foo\Bar\Qux\QuuxTest class from /path/to/packages/foo-bar/tests/Qux/QuuxTest.php:
 * 下面代碼將用/path/to/packages/foo-bar/tests/Qux/QuuxTest.php文件來加載
 * \Foo\Bar\Qux\QuuxTest類。
 * 
 *      <?php
 *      new \Foo\Bar\Qux\QuuxTest;
 */
class Psr4AutoloaderClass
{
    /**
     * An associative array where the key is a namespace prefix and the value
     * is an array of base directories for classes in that namespace.
     * 定義一個數組:key爲命名空間前綴,value爲一個數組,每一項表示命名空間中類對應的base目錄.
     *
     * @var array
     */
    protected $prefixes = array();

    /**
     * Register loader with SPL autoloader stack.
     * 利用SPL自動加載器來註冊loader
     * 
     * @return void
     */
    public function register()
    {
        spl_autoload_register(array($this, 'loadClass'));
    }

    /**
     * Adds a base directory for a namespace prefix.
     * 爲一個命名空間前綴添加對應的base目錄
     *
     * @param string $prefix The namespace prefix.
     * @param string $base_dir A base directory for class files in the
     * namespace.
     * @param bool $prepend If true, prepend the base directory to the stack
     * instead of appending it; this causes it to be searched first rather
     * than last.
     * @return void
     */
    public function addNamespace($prefix, $base_dir, $prepend = false)
    {
        // normalize namespace prefix
        // 規範命名空間前綴
        $prefix = trim($prefix, '\\') . '\\';

        // normalize the base directory with a trailing separator
        // 用'/'字符來規範base目錄
        $base_dir = rtrim($base_dir, DIRECTORY_SEPARATOR) . '/';

        // initialize the namespace prefix array
        // 初始化命名空間前綴數組
        if (isset($this->prefixes[$prefix]) === false) {
            $this->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. 單元測試

    下面是對應的單元測試代碼:

<?php
namespace Example\Tests;

class MockPsr4AutoloaderClass extends Psr4AutoloaderClass
{
    protected $files = array();

    public function setFiles(array $files)
    {
        $this->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/

相關文章
相關標籤/搜索