Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...