如何为我的项目创建PSR-4自动装带器? [英] How to create a PSR-4 autoloader for my project?

查看:59
本文介绍了如何为我的项目创建PSR-4自动装带器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个PHP项目,并希望实现PSR-4自动加载.

I am creating a PHP project and want to implement PSR-4 autoloading.

我不知道我需要在vendor目录中创建哪些文件来实现类文件的自动加载.

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 App\Controller;

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 App\Controller\Home;

$homeController = new Home();

此处中对此进行了解释.

这篇关于如何为我的项目创建PSR-4自动装带器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆