资讯专栏INFORMATION COLUMN

PSR-4——新鲜出炉的PHP规范

Fundebug / 1326人阅读

摘要:制定的规范,简称,是开发的事实标准。原本有四个规范,分别是自动加载基本代码规范代码样式日志接口年底,新出了第个规范。区别在于的规范比较干净,去除了兼容以前版本的内容,有一点升级版的感觉。

FIG制定的PHP规范,简称PSR,是PHP开发的事实标准。

PSR原本有四个规范,分别是:

PSR-0 自动加载

PSR-1 基本代码规范

PSR-2 代码样式

PSR-3 日志接口

2013年底,新出了第5个规范——PSR-4。

PSR-4规范了如何指定文件路径从而自动加载类定义,同时规范了自动加载文件的位置。这个乍一看和PSR-0重复了,实际上,在功能上确实有所重复。区别在于PSR-4的规范比较干净,去除了兼容PHP 5.3以前版本的内容,有一点PSR-0升级版的感觉。当然,PSR-4也不是要完全替代PSR-0,而是在必要的时候补充PSR-0——当然,如果你愿意,PSR-4也可以替代PSR-0。PSR-4可以和包括PSR-0在内的其他自动加载机制共同使用。

PSR-4和PSR-0最大的区别是对下划线(underscore)的定义不同。PSR-4中,在类名中使用下划线没有任何特殊含义。而PSR-0则规定类名中的下划线_会被转化成目录分隔符。

代码样例

以下代码展示了遵循PSR-4的类定义,这个类处理多个命名空间:

register();
 *      
 *      // register the base directories for the namespace prefix
 *      $loader->addNamespace("FooBar", "/path/to/packages/foo-bar/src");
 *      $loader->addNamespace("FooBar", "/path/to/packages/foo-bar/tests");
 * 
 * The following line would cause the autoloader to attempt to load the
 * FooBarQuxQuux class from /path/to/packages/foo-bar/src/Qux/Quux.php:
 * 
 *      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;
    }
}

相应的单元测试代码

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(
            "FooBar",
            "/vendor/foo.bar/src"
        );

        $this->loader->addNamespace(
            "FooBar",
            "/vendor/foo.bar/tests"
        );

        $this->loader->addNamespace(
            "FooBarDoom",
            "/vendor/foo.bardoom/src"
        );

        $this->loader->addNamespace(
            "FooBarBazDib",
            "/vendor/foo.bar.baz.dib/src"
        );

        $this->loader->addNamespace(
            "FooBarBazDibimGir",
            "/vendor/foo.bar.baz.dib.zim.gir/src"
        );
    }

    public function testExistingFile()
    {
        $actual = $this->loader->loadClass("FooBarClassName");
        $expect = "/vendor/foo.bar/src/ClassName.php";
        $this->assertSame($expect, $actual);

        $actual = $this->loader->loadClass("FooBarClassNameTest");
        $expect = "/vendor/foo.bar/tests/ClassNameTest.php";
        $this->assertSame($expect, $actual);
    }

    public function testMissingFile()
    {
        $actual = $this->loader->loadClass("No_VendorNo_PackageNoClass");
        $this->assertFalse($actual);
    }

    public function testDeepFile()
    {
        $actual = $this->loader->loadClass("FooBarBazDibimGirClassName");
        $expect = "/vendor/foo.bar.baz.dib.zim.gir/src/ClassName.php";
        $this->assertSame($expect, $actual);
    }

    public function testConfusion()
    {
        $actual = $this->loader->loadClass("FooBarDoomClassName");
        $expect = "/vendor/foo.bar/src/DoomClassName.php";
        $this->assertSame($expect, $actual);

        $actual = $this->loader->loadClass("FooBarDoomClassName");
        $expect = "/vendor/foo.bardoom/src/ClassName.php";
        $this->assertSame($expect, $actual);
    }
}
Composer

PHP的包管理系统Composer已经支持PSR-4,同时也允许在composer.json中定义不同的prefix使用不同的自动加载机制。

Composer使用PSR-0风格

vendor/
    vendor_name/
        package_name/
            src/
                Vendor_Name/
                    Package_Name/
                        ClassName.php       # Vendor_NamePackage_NameClassName
            tests/
                Vendor_Name/
                    Package_Name/
                        ClassNameTest.php   # Vendor_NamePackage_NameClassName

Composer使用PSR-4风格

vendor/
    vendor_name/
        package_name/
            src/
                ClassName.php       # Vendor_NamePackage_NameClassName
            tests/
                ClassNameTest.php   # Vendor_NamePackage_NameClassNameTest

对比以上两种结构,明显可以看出PSR-4带来更简洁的文件结构。


撰文 SegmentFault

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/20643.html

相关文章

  • PHP自动加载功能原理解析

    摘要:前言在开始之前,欢迎关注我自己的博客这篇文章是对自动加载功能的一个总结,内容涉及的自动加载功能的命名空间的与标准等内容。要实现第一步,第二步的功能,必须在开发时约定类名与磁盘文件的映射方法,只有这样我们才能根据类名找到它对应的磁盘文件。 前言 在开始之前,欢迎关注我自己的博客:www.leoyang90.cn 这篇文章是对PHP自动加载功能的一个总结,内容涉及PHP的自动加载功能、P...

    Imfan 评论0 收藏0
  • PHP 标准规范

    摘要:标准规范简介是的简写,由组织制定的规范,是开发的实践标准。具体标准有有了统一编码风格规范,更有利于查看和学习各个框架或类库,不不需要每次都适应新的编码风格。同时在开发团队内部使用统一的编码规范更有利于代码审查版本控制团队内部交流。 PHP 标准规范 PSR PSR 简介 PSR 是 PHP Standard Recommendations 的简写,由 PHP FIG 组织制定的 PHP...

    FuisonDesign 评论0 收藏0
  • PHPPSR简要规范

    摘要:是一系列关于开发的规范,分有好几个版本,自己学的也较为肤浅,但还是希望能时常查看规范,为了方便记忆和遵循,我把关键词为必须的捡拾出来,做个简单地必要规范的记录。所有文件必须使用作为行的结束符。 PSR是一系列关于PHP开发的规范,分有好几个版本,自己学的也较为肤浅,但还是希望能时常查看规范,为了方便记忆和遵循,我把关键词为必须的捡拾出来,做个简单地必要规范的记录。(就是个搬砖的。。。)...

    Steve_Wang_ 评论0 收藏0
  • php-psr-chinese psr规范总结

    摘要:公认规范总结规范中文版大部分来源翻译部分包含例子,附录包含了一些规范的实现基本编码标准编码风格指南日志接口规范自动加载规范规范英文版未使用草案已弃用规范原理实现实现自动加载实现原理资料来源与参考 PSR公认规范总结 PSR规范中文版(大部分来源google翻译)(cn) 部分psr包含例子,附录包含了一些规范的实现 PSR-1:基本编码标准 PSR-2:编码风格指南 PSR-3:日志...

    tuomao 评论0 收藏0
  • PSR-1 Basic Coding Standard(译)-- 基础编码规范

    摘要:注本文算是笔者对规范翻译学习笔记,之后会陆续翻译剩余的规范,可能翻译的有错误的地方,希望读者能够指正,非常感谢什么是是标准建议的简写,是由组织框架交互操作组织提出。的工作是寻找项目之间的共性,以及让开发者能更好协同工作的方式。 注:本文算是笔者对PSR规范翻译/学习笔记,之后会陆续翻译剩余的规范,可能翻译的有错误的地方,希望读者能够指正,非常感谢. 什么是PSR?       PSR是...

    darryrzhong 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<