简体   繁体   English

PHP - PSR-4:自动加载器(编写器)和具有相同根的多个名称空间

[英]PHP - PSR-4: Autoloader (composer) and multiple namespaces with the same root

Currently all my classes are in one folder and are under one namespace: 目前我的所有类都在一个文件夹中并且位于一个名称空间下:

"psr-4": {
   "RootNamespace\\": "lib/"
},

This is working well. 这很好用。 As I'm adding more and more classes, I would like to put some logically related classes into deeper namespace level, but with the same root namespace. 当我添加越来越多的类时,我想将一些逻辑上相关的类放入更深的命名空间级别,但具有相同的根命名空间。 It should be something like this: 它应该是这样的:

RootNamespace/Services (in 'lib/services' dir)
RootNamespace/Listeners (in 'lib/listeners' dir)

I suppose so that I don't need to change anything in my composer.json ps-4 autoload definition, but it's not working anymore. 我想我不需要在composer.json ps-4自动加载定义中更改任何内容,但它不再起作用了。

How autoload definition should look like to achieve what I want to? 自动加载定义应如何实现我想要的目标?

As I tested, solution below is not a good since, declarations seems to be overwritten 正如我测试的那样,下面的解决方案并不好,因为声明似乎被覆盖了

"psr-4": {
   "RootNamespace\\": "lib/",
   "RootNamespace\\Services\\": "lib/services/",
   "RootNamespace\\Listeners\\": "lib/listeners/"
},

According to the PSR-4 Spec : 根据PSR-4规格

All class names MUST be referenced in a case-sensitive fashion. 必须以区分大小写的方式引用所有类名。

Your configuration is accurate having different PSR-4 namespaces nested in the same directory. 您的配置是准确的,具有嵌套在同一目录中的不同PSR-4命名空间。 It should work, but may become confusing down the road. 它应该工作,但可能会变得混乱。

"psr-4": {
    "RootNamespace\\": "lib/",
    "RootNamespace\\Services\\": "lib/services/",
    "RootNamespace\\Listeners\\": "lib/listeners/"
},

I recommend you either simply capitalize your directories to match the PSR spec, or move your RootNamespace out of the top level lib/ directory. 我建议您只需将目录大写以匹配PSR规范,或将RootNamespace移出顶级lib/目录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM