如何为我的项目创建 PSR-4 自动加载器? [英] How to create a PSR-4 autoloader for my project?
问题描述
我正在创建一个 PHP 项目并希望实现 PSR-4 自动加载.
I am creating a PHP project and want to implement PSR-4 autoloading.
我不知道我需要在供应商目录中创建哪些文件来实现类文件的自动加载.
I don't know which files I need to create in the vendor directory to implement autoloading for class files.
推荐答案
如果您正在使用 composer
,您不需要创建自动加载器,而是让 composer
完成它的工作并且为您创建.
If you are using composer
, you do not create the autoloader but let composer
do its job and create it for you.
您唯一需要做的就是在 composer.json
上创建适当的配置并执行 composer dump-autoload
.
The only thing you need to do is create the appropriate configuration on composer.json
and execute composer dump-autoload
.
例如:
{
"autoload": {
"psr-4": {"App\": "src/"}
}
}
通过执行上述操作,如果您有这样的文件结构
By doing the above, if you have a file structure like this
├── src/
│ ├── Controller/
│ ├── Model/
│ ├── View/
│ └── Kernel.php
├── public/
│ └── index.php
└── vendor/
执行composer dump-autoload
后,自动加载器将在vendor/autoload.php
上生成.
After executing composer dump-autoload
the autoloader will be generated on vendor/autoload.php
.
您的所有类都应该嵌套在 App
命名空间中,并且每个文件应该只放置一个类.
All your classes should be nested inside the App
namespace, and you should put only one class per file.
例如:
<?php /* src/Controller/Home.php */
namespace AppController;
class Home { /* implementation */ }
并且您只需要在入口点脚本中包含自动加载器(例如 index.php
).
And you need only to include the autoloader in your entry-point script (e.g. index.php
).
<?php
require '../vendor/autoload.php';
这将允许您在此之后从任何地方直接加载您的类,如下所示:
Which will allow you to simply load your classes directly from anywhere after this point, like this:
use AppControllerHome;
$homeController = new Home();
这在文档中进行了解释,此处.
This is explained at the docs, here.
这篇关于如何为我的项目创建 PSR-4 自动加载器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!