How to create a PSR-4 autoloader for my project?

假如想象 提交于 2021-01-28 03:06:17

问题


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.


回答1:


If you are using composer, you do not create the autoloader but let composer do its job and create it for you.

The only thing you need to do is create the appropriate configuration on composer.json and execute composer dump-autoload.

E.g.:

{
    "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/

After executing composer dump-autoload the autoloader will be generated on vendor/autoload.php.

All your classes should be nested inside the App namespace, and you should put only one class per file.

E.g.:

<?php /* src/Controller/Home.php */

namespace App\Controller;

class Home { /* implementation */ }

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();

This is explained at the docs, here.



来源:https://stackoverflow.com/questions/60918843/how-to-create-a-psr-4-autoloader-for-my-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!