PSR-4自动加载如何在自定义库的composer中工作? [英] How does PSR-4 autoloading work in composer for custom libraries?
问题描述
基于对PHP中名称空间的工作原理的理解,我使用以下目录结构:
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
根据PSR-4规范,完全限定的类名称具有以下形式:
According to the PSR-4 specification, a fully qualified class name has the following form:
\<NamespaceName>(\<SubNamespaceNames>)*\<ClassName>
问题1:
根据我上面的目录结构,下面的假设正确吗?
From my directory structure above, is the assumption below correct?
- NamespaceName = MyCompany
- SubNamespaceNames =实用工具|核心
- ClassName =记录器|用户
问题2:
如果我的bootstrap.php文件包含以下内容:
If my bootstrap.php file contains the following:
<?php
require 'vendor/autoload.php';
我将如何配置作曲家的自动加载" 部分. json以自动加载MyCompany目录中的类?这样我就可以在bootstrap.php中创建Logger的实例
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/",
}
}
}
这很容易解释,它只是告诉自动加载器app/lib/MyCompany
是MyCompany\
名称空间的根.
This is pretty self explanatory, it simply tells the autoloader that app/lib/MyCompany
is the root for the MyCompany\
namespace.
然后您就可以将该类用作\MyCompany\Utility\Logger
.
You would then be able to use the class as \MyCompany\Utility\Logger
.
请注意,在PSR-4中,与PSR-0不同,通常会从目录结构中省略MyCompany
,而只需使用app/lib/
.
Note that in PSR-4, unlike PSR-0, you'd normally omit MyCompany
from the directory structure, and just use app/lib/
.
这篇关于PSR-4自动加载如何在自定义库的composer中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!