• 喜欢前端以及PHP的朋友们可以加PHP同好会QQ群 点击加入qq群
  • 最近在写一个项目---"小A微信托管平台",大家可以去帮忙测试一下!功能在不断完善中,敬请关注!点击进入
  • 本站使用了PHP8.1与HTTP2.0协议,速度简直超级快有木有?

psr-4 规范(php的类自动加载规范)

后端 Mr.Adam 8年前 (2017-04-13) 2352次浏览 已收录 0个评论

psr-4 规范(php 的类自动加载规范)

psr-4 规范(php 的类自动加载规范)

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. <?php
  2. namespace Example;
  3.  
  4. /**
  5. * An example of a general-purpose implementation that includes the optional
  6. * functionality of allowing multiple base directories for a single namespace
  7. * prefix.
  8. *
  9. * Given a foo-bar package of classes in the file system at the following
  10. * paths ...
  11. *
  12. * /path/to/packages/foo-bar/
  13. * src/
  14. * Baz.php # Foo\Bar\Baz
  15. * Qux/
  16. * Quux.php # Foo\Bar\Qux\Quux
  17. * tests/
  18. * BazTest.php # Foo\Bar\BazTest
  19. * Qux/
  20. * QuuxTest.php # Foo\Bar\Qux\QuuxTest
  21. *
  22. * ... add the path to the class files for the \Foo\Bar\ namespace prefix
  23. * as follows:
  24. *
  25. * <?php
  26. * // instantiate the loader
  27. * $loader = new \Example\Psr4AutoloaderClass;
  28. *
  29. * // register the autoloader
  30. * $loader->register();
  31. *
  32. * // register the base directories for the namespace prefix
  33. * $loader->addNamespace('Foo\Bar', '/path/to/packages/foo-bar/src');
  34. * $loader->addNamespace('Foo\Bar', '/path/to/packages/foo-bar/tests');
  35. *
  36. * The following line would cause the autoloader to attempt to load the
  37. * \Foo\Bar\Qux\Quux class from /path/to/packages/foo-bar/src/Qux/Quux.php:
  38. *
  39. * <?php
  40. * new \Foo\Bar\Qux\Quux;
  41. *
  42. * The following line would cause the autoloader to attempt to load the
  43. * \Foo\Bar\Qux\QuuxTest class from /path/to/packages/foo-bar/tests/Qux/QuuxTest.php:
  44. *
  45. * <?php
  46. * new \Foo\Bar\Qux\QuuxTest;
  47. */
  48. class Psr4AutoloaderClass
  49. {
  50. /**
  51. * An associative array where the key is a namespace prefix and the value
  52. * is an array of base directories for classes in that namespace.
  53. *
  54. * @var array
  55. */
  56. protected $prefixes = array();
  57.  
  58. /**
  59. * Register loader with SPL autoloader stack.
  60. *
  61. * @return void
  62. */
  63. public function register()
  64. {
  65. spl_autoload_register(array($this, 'loadClass'));
  66. }
  67.  
  68. /**
  69. * Adds a base directory for a namespace prefix.
  70. *
  71. * @param string $prefix The namespace prefix.
  72. * @param string $base_dir A base directory for class files in the
  73. * namespace.
  74. * @param bool $prepend If true, prepend the base directory to the stack
  75. * instead of appending it; this causes it to be searched first rather
  76. * than last.
  77. * @return void
  78. */
  79. public function addNamespace($prefix, $base_dir, $prepend = false)
  80. {
  81. // normalize namespace prefix
  82. $prefix = trim($prefix, '\\') . '\\';
  83.  
  84. // normalize the base directory with a trailing separator
  85. $base_dir = rtrim($base_dir, DIRECTORY_SEPARATOR) . '/';
  86.  
  87. // initialize the namespace prefix array
  88. if (isset($this->prefixes[$prefix]) === false) {
  89. $this->prefixes[$prefix] = array();
  90. }
  91.  
  92. // retain the base directory for the namespace prefix
  93. if ($prepend) {
  94. array_unshift($this->prefixes[$prefix], $base_dir);
  95. } else {
  96. array_push($this->prefixes[$prefix], $base_dir);
  97. }
  98. }
  99.  
  100. /**
  101. * Loads the class file for a given class name.
  102. *
  103. * @param string $class The fully-qualified class name.
  104. * @return mixed The mapped file name on success, or boolean false on
  105. * failure.
  106. */
  107. public function loadClass($class)
  108. {
  109. // the current namespace prefix
  110. $prefix = $class;
  111.  
  112. // work backwards through the namespace names of the fully-qualified
  113. // class name to find a mapped file name
  114. while (false !== $pos = strrpos($prefix, '\\')) {
  115.  
  116. // retain the trailing namespace separator in the prefix
  117. $prefix = substr($class, 0, $pos + 1);
  118.  
  119. // the rest is the relative class name
  120. $relative_class = substr($class, $pos + 1);
  121.  
  122. // try to load a mapped file for the prefix and relative class
  123. $mapped_file = $this->loadMappedFile($prefix, $relative_class);
  124. if ($mapped_file) {
  125. return $mapped_file;
  126. }
  127.  
  128. // remove the trailing namespace separator for the next iteration
  129. // of strrpos()
  130. $prefix = rtrim($prefix, '\\');
  131. }
  132.  
  133. // never found a mapped file
  134. return false;
  135. }
  136.  
  137. /**
  138. * Load the mapped file for a namespace prefix and relative class.
  139. *
  140. * @param string $prefix The namespace prefix.
  141. * @param string $relative_class The relative class name.
  142. * @return mixed Boolean false if no mapped file can be loaded, or the
  143. * name of the mapped file that was loaded.
  144. */
  145. protected function loadMappedFile($prefix, $relative_class)
  146. {
  147. // are there any base directories for this namespace prefix?
  148. if (isset($this->prefixes[$prefix]) === false) {
  149. return false;
  150. }
  151.  
  152. // look through base directories for this namespace prefix
  153. foreach ($this->prefixes[$prefix] as $base_dir) {
  154.  
  155. // replace the namespace prefix with the base directory,
  156. // replace namespace separators with directory separators
  157. // in the relative class name, append with .php
  158. $file = $base_dir
  159. . str_replace('\\', '/', $relative_class)
  160. . '.php';
  161.  
  162. // if the mapped file exists, require it
  163. if ($this->requireFile($file)) {
  164. // yes, we're done
  165. return $file;
  166. }
  167. }
  168.  
  169. // never found it
  170. return false;
  171. }
  172.  
  173. /**
  174. * If a file exists, require it from the file system.
  175. *
  176. * @param string $file The file to require.
  177. * @return bool True if the file exists, false if not.
  178. */
  179. protected function requireFile($file)
  180. {
  181. if (file_exists($file)) {
  182. require $file;
  183. return true;
  184. }
  185. return false;
  186. }
  187. }

小 A 空间 , 版权所有丨如未注明转载 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明psr-4 规范(php 的类自动加载规范)
喜欢 (2)
发表我的评论
取消评论
表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址