资讯专栏INFORMATION COLUMN

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

Fundebug / 1482人阅读

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

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的类定义,这个类处理多个命名空间:

</>复制代码

  1. register();
  2. *
  3. * // register the base directories for the namespace prefix
  4. * $loader->addNamespace("FooBar", "/path/to/packages/foo-bar/src");
  5. * $loader->addNamespace("FooBar", "/path/to/packages/foo-bar/tests");
  6. *
  7. * The following line would cause the autoloader to attempt to load the
  8. * FooBarQuxQuux class from /path/to/packages/foo-bar/src/Qux/Quux.php:
  9. *
  10. * prefixes[$prefix]) === false) {
  11. $this->prefixes[$prefix] = array();
  12. }
  13. // retain the base directory for the namespace prefix
  14. if ($prepend) {
  15. array_unshift($this->prefixes[$prefix], $base_dir);
  16. } else {
  17. array_push($this->prefixes[$prefix], $base_dir);
  18. }
  19. }
  20. /**
  21. * Loads the class file for a given class name.
  22. *
  23. * @param string $class The fully-qualified class name.
  24. * @return mixed The mapped file name on success, or boolean false on
  25. * failure.
  26. */
  27. public function loadClass($class)
  28. {
  29. // the current namespace prefix
  30. $prefix = $class;
  31. // work backwards through the namespace names of the fully-qualified
  32. // class name to find a mapped file name
  33. while (false !== $pos = strrpos($prefix, "")) {
  34. // retain the trailing namespace separator in the prefix
  35. $prefix = substr($class, 0, $pos + 1);
  36. // the rest is the relative class name
  37. $relative_class = substr($class, $pos + 1);
  38. // try to load a mapped file for the prefix and relative class
  39. $mapped_file = $this->loadMappedFile($prefix, $relative_class);
  40. if ($mapped_file) {
  41. return $mapped_file;
  42. }
  43. // remove the trailing namespace separator for the next iteration
  44. // of strrpos()
  45. $prefix = rtrim($prefix, "");
  46. }
  47. // never found a mapped file
  48. return false;
  49. }
  50. /**
  51. * Load the mapped file for a namespace prefix and relative class.
  52. *
  53. * @param string $prefix The namespace prefix.
  54. * @param string $relative_class The relative class name.
  55. * @return mixed Boolean false if no mapped file can be loaded, or the
  56. * name of the mapped file that was loaded.
  57. */
  58. protected function loadMappedFile($prefix, $relative_class)
  59. {
  60. // are there any base directories for this namespace prefix?
  61. if (isset($this->prefixes[$prefix]) === false) {
  62. return false;
  63. }
  64. // look through base directories for this namespace prefix
  65. foreach ($this->prefixes[$prefix] as $base_dir) {
  66. // replace the namespace prefix with the base directory,
  67. // replace namespace separators with directory separators
  68. // in the relative class name, append with .php
  69. $file = $base_dir
  70. . str_replace("", DIRECTORY_SEPARATOR, $relative_class)
  71. . ".php";
  72. $file = $base_dir
  73. . str_replace("", "/", $relative_class)
  74. . ".php";
  75. // if the mapped file exists, require it
  76. if ($this->requireFile($file)) {
  77. // yes, we"re done
  78. return $file;
  79. }
  80. }
  81. // never found it
  82. return false;
  83. }
  84. /**
  85. * If a file exists, require it from the file system.
  86. *
  87. * @param string $file The file to require.
  88. * @return bool True if the file exists, false if not.
  89. */
  90. protected function requireFile($file)
  91. {
  92. if (file_exists($file)) {
  93. require $file;
  94. return true;
  95. }
  96. return false;
  97. }
  98. }

相应的单元测试代码

</>复制代码

  1. files = $files;
  2. }
  3. protected function requireFile($file)
  4. {
  5. return in_array($file, $this->files);
  6. }
  7. }
  8. class Psr4AutoloaderClassTest extends PHPUnit_Framework_TestCase
  9. {
  10. protected $loader;
  11. protected function setUp()
  12. {
  13. $this->loader = new MockPsr4AutoloaderClass;
  14. $this->loader->setFiles(array(
  15. "/vendor/foo.bar/src/ClassName.php",
  16. "/vendor/foo.bar/src/DoomClassName.php",
  17. "/vendor/foo.bar/tests/ClassNameTest.php",
  18. "/vendor/foo.bardoom/src/ClassName.php",
  19. "/vendor/foo.bar.baz.dib/src/ClassName.php",
  20. "/vendor/foo.bar.baz.dib.zim.gir/src/ClassName.php",
  21. ));
  22. $this->loader->addNamespace(
  23. "FooBar",
  24. "/vendor/foo.bar/src"
  25. );
  26. $this->loader->addNamespace(
  27. "FooBar",
  28. "/vendor/foo.bar/tests"
  29. );
  30. $this->loader->addNamespace(
  31. "FooBarDoom",
  32. "/vendor/foo.bardoom/src"
  33. );
  34. $this->loader->addNamespace(
  35. "FooBarBazDib",
  36. "/vendor/foo.bar.baz.dib/src"
  37. );
  38. $this->loader->addNamespace(
  39. "FooBarBazDibimGir",
  40. "/vendor/foo.bar.baz.dib.zim.gir/src"
  41. );
  42. }
  43. public function testExistingFile()
  44. {
  45. $actual = $this->loader->loadClass("FooBarClassName");
  46. $expect = "/vendor/foo.bar/src/ClassName.php";
  47. $this->assertSame($expect, $actual);
  48. $actual = $this->loader->loadClass("FooBarClassNameTest");
  49. $expect = "/vendor/foo.bar/tests/ClassNameTest.php";
  50. $this->assertSame($expect, $actual);
  51. }
  52. public function testMissingFile()
  53. {
  54. $actual = $this->loader->loadClass("No_VendorNo_PackageNoClass");
  55. $this->assertFalse($actual);
  56. }
  57. public function testDeepFile()
  58. {
  59. $actual = $this->loader->loadClass("FooBarBazDibimGirClassName");
  60. $expect = "/vendor/foo.bar.baz.dib.zim.gir/src/ClassName.php";
  61. $this->assertSame($expect, $actual);
  62. }
  63. public function testConfusion()
  64. {
  65. $actual = $this->loader->loadClass("FooBarDoomClassName");
  66. $expect = "/vendor/foo.bar/src/DoomClassName.php";
  67. $this->assertSame($expect, $actual);
  68. $actual = $this->loader->loadClass("FooBarDoomClassName");
  69. $expect = "/vendor/foo.bardoom/src/ClassName.php";
  70. $this->assertSame($expect, $actual);
  71. }
  72. }
Composer

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

Composer使用PSR-0风格

</>复制代码

  1. vendor/
  2. vendor_name/
  3. package_name/
  4. src/
  5. Vendor_Name/
  6. Package_Name/
  7. ClassName.php # Vendor_NamePackage_NameClassName
  8. tests/
  9. Vendor_Name/
  10. Package_Name/
  11. ClassNameTest.php # Vendor_NamePackage_NameClassName

Composer使用PSR-4风格

</>复制代码

  1. vendor/
  2. vendor_name/
  3. package_name/
  4. src/
  5. ClassName.php # Vendor_NamePackage_NameClassName
  6. tests/
  7. 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元查看
<