6

PSR-0 ( https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md ) 标准规定类名中的下划线应转换为目录分隔符对应的文件名。

对我来说,这似乎不是一个好主意,因为当不知道标准的人在类名中无辜地使用下划线并且突然自动加载器找不到类并且出现各种奇怪的错误时,它会产生很多错误(参见这个stackoverflow问题例如:Symfony2.1 mapping error: class_parents() )

所以我想这个“功能”一定有某种原因(与某些库的历史兼容性?)。我的问题是:有人知道为什么在 PSR-0 标准中引入了这一点吗?

4

3 回答 3

6

在 PHP 还不支持命名空间的时候使用了下划线。一个“正确”的组织项目遵循与目录结构相同的命名空间约定。

在项目中组织文件只是一些一般的“规则”。

因此,如果您的目录结构为:

root
  Name
    Package
      MyClass.php

人们曾经这样做:

class Name_Package_MyClass {}

但是现在我们有了命名空间,它变成了:

namespace Name\Package;

class MyClass { }

这只是编码风格指南,可确保每个人都做同样的事情。

所以 PSR-0 所做的是将旧的和新的命名空间样式映射到文件名。

于 2012-07-27T22:02:57.143 回答
1

PHP supports namespaces since version 5.3, earlier the most common convention was to use underscore as namespace (directory) separator, e.g.: My_Project_ClassName was mapped as /path/to/my/My/Project/ClassName. I believe that backwards compatibility is the main reason.

于 2012-07-27T22:05:07.987 回答
1

Keep in mind that the PSR-0 standard was written for a few specific projects and not necessarily the best option for your own project. As it says on their site: "If other folks want to adopt what we’re doing they are welcome to do so, but that is not the aim." PSR-0 is very restrictive, I wouldn't choose to use it just because other people are. Consider what you actually want from your project and whether it will be beneficial for you.

于 2013-04-15T08:24:05.853 回答