PSR-4 and PSR-0

Source: Internet
Author: User
Tags autoloader

PHP psr-0 psr-4 autoloading composer

In the previous article, we introduced PSR-0 and autoload-related content. Following the PSR-0, the PHP autoloading specification, the PHP-FIG has introduced a PSR-4 called the improved autoloading specification.

In the PSR-0, \ symfony \ core \ request will be converted to the/path/to/project/lib/vendor/symfony/CORE/request. php path of the file system. PSR-4 and PSR-0 in the content of the difference is not big.

I will not discuss the definitions of the two in detail here. Let's take a look at the differences between the two. Due to the popularity of composer, the two composer styles are compared here.

In composer, the typical directory structure following the PSR-0 standards is as follows:

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\ClassNameTest

We can see that the directory structure is obviously repeated and has a deep hierarchy. The src/and test/directories re-contain the vendor and package directories.

Let's take a look at the PSR-4:

vendor/    vendor_name/        package_name/            src/                ClassName.php       # Vendor_Name\Package_Name\ClassName            tests/                ClassNameTest.php   # Vendor_Name\Package_Name\ClassNameTest
The directory structure is more concise.

In the PSR-0, the directory structure must correspond to the namespace layers, and a separate directory cannot be inserted. While PSR-4 can.

Contrast PSR-0, in addition to PSR-4 can be more concise, need to note that the PSR-0 of the underline (_) is a special treatment, the underline will be converted to directory_separator, this is out of considerations for php5.3 earlier versions of compatibility, and the PSR-4 does not have this processing, which is a big difference between the two.

In addition, the PSR-4 requires that the throws and throws of any level of errors are not allowed in autoloader, and there should be no returned values. This is because multiple Autoloaders may be registered. If an autoloader does not find the corresponding class, it should be handed over to the next one for processing, rather than blocking this channel.

PSR-4 is more concise and flexible, but it makes it more complicated. For example, by fully complying with the PSR-0 standard class name, you can usually clearly know the path of this class, And the PSR-4 may not be like this.

Given a foo-bar package of classes in the file system at the following paths... /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: <? PHP // instantiate the loader $ loader = new \ example \ psr4autoloaderclass; // register the autoloader $ loader-> Register (); // register the base directories for the namespace prefix $ loader-> addnamespace ('foo \ bar', '/path/to/packages/foo-bar/src '); $ loader-> addnamespace ('foo \ bar', '/path/to/packages/foo-bar/tests '); // At this time, a namespace prefix corresponds to multiple "base directory" // autoloader loads/path/to/packages/foo-bar/src/qux/quux. PHP new \ Foo \ bar \ qux \ quux; // autoloader loads/path/to/packages/foo-bar/tests/qux/quuxtest. PHP new \ Foo \ bar \ qux \ quuxtest;

The following is the implementation of the above PSR-4 autoloader:

<?phpnamespace Example;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.     *     * @var array     */    protected $prefixes = array();    /**     * Register loader with SPL autoloader stack.     *      * @return void     */    public function register()    {        spl_autoload_register(array($this, 'loadClass'));    }    /**     * Adds a base directory for a namespace prefix.     *     * @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_dir = rtrim($base_dir, '/') . DIRECTORY_SEPARATOR;        $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        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()            $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?        if (isset($this->prefixes[$prefix]) === false) {            return false;        }        // look through base directories for this namespace prefix        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            $file = $base_dir                  . str_replace('\\', DIRECTORY_SEPARATOR, $relative_class)                  . '.php';            $file = $base_dir                  . str_replace('\\', '/', $relative_class)                  . '.php';            // if the mapped file exists, require it            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;    }}
Unit test code:

<?phpnamespace 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);    }}

.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.