Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
409 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 AppController;

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 AppControllerHome;

$homeController = new Home();

This is explained at the docs, here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...