PSR-4 自动加载如何在 composer 中为自定义库工作?
根据我对 PHP 中命名空间如何工作的理解,我使用以下目录结构:
project_root应用程序/|库/||我的公司/|||公用事业/||||记录器.php|||核/||||用户.php小贩/作曲家/symfony/狂饮/引导程序.php作曲家.json
根据 PSR-4 规范,完全限定的类名具有以下形式:
<NamespaceName>(<SubNamespaceNames>)*<ClassName>
问题 1:
从我上面的目录结构来看,下面的假设是否正确?
- 命名空间名称 = 我的公司
- 子名称空间名称 = 实用程序 |核心
- 类名 = 记录器 |用户
问题 2:
如果我的 bootstrap.php 文件包含以下内容:
我将如何配置作曲家的自动加载"部分.json 自动加载 MyCompany 目录中的类?这样我就可以在 bootstrap.php 中创建一个 Logger 实例
解决方案取自您链接的文档:
<代码>{自动加载":{psr-4":{"MyCompany\": "app/lib/MyCompany/",}}}
这很容易解释,它只是告诉自动加载器 app/lib/MyCompany
是 MyCompany
命名空间的根.
然后您就可以将该类用作 MyCompanyUtilityLogger
.
请注意,在 PSR-4 中,与 PSR-0 不同,您通常会从目录结构中省略 MyCompany
,而只使用 app/lib/
.p>
I use the following directory structure based on my understanding of how namespaces in PHP work:
project_root
app/
| lib/
| | MyCompany/
| | | Utility/
| | | | Logger.php
| | | Core/
| | | | User.php
vendor/
composer/
symfony/
guzzle/
bootstrap.php
composer.json
According to the PSR-4 specification, a fully qualified class name has the following form:
<NamespaceName>(<SubNamespaceNames>)*<ClassName>
Question 1:
From my directory structure above, is the assumption below correct?
- NamespaceName = MyCompany
- SubNamespaceNames = Utility | Core
- ClassName = Logger | User
Question 2:
If my bootstrap.php file contains the following:
<?php
require 'vendor/autoload.php';
How would I configure the 'autoload' section of composer.json to autoload the classes in the MyCompany directory? Such that I would be able to create an instance of Logger in bootstrap.php
解决方案Taken from the documentation you linked:
{
"autoload": {
"psr-4": {
"MyCompany\": "app/lib/MyCompany/",
}
}
}
This is pretty self explanatory, it simply tells the autoloader that app/lib/MyCompany
is the root for the MyCompany
namespace.
You would then be able to use the class as MyCompanyUtilityLogger
.
Note that in PSR-4, unlike PSR-0, you'd normally omit MyCompany
from the directory structure, and just use app/lib/
.
相关文章