Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

SangminKim's avatar

Autoload psr-4 in composer.json

Hello everyone,

I'd like to ask a few questions about autoload in composer.json. I was looking into this tutorial on publishing my own package to packagist... and got confused with what autoload in composer.json does.

https://pusher.com/tutorials/publish-laravel-packagist

Here are my questions...

A. What does autoload (espcially psr-4) in Laravel do in the background?

B. Why should each package have its own autoload psr-4? What is this for? ex)

 "autoload": {
            "psr-4": {
                "MyVendor\contactform\": "src/"
            }
        }

C. Why do we add another autoload psr-4 to Laravel's composer.json? What is this for? ex)

"autoload": {
            "classmap": [
                "database/seeds",
                "database/factories"
            ],
            "psr-4": {
                "MyVendor\Contactform\": "packages/MyVendor/contactform/src",
                "App\": "app/"
            }
        }

D. What's the relationship between this and the service provider list in config/app.php? It looks like I still need to add the custom package's service provider to app.php anyway. Then, what's the point of doing 'autoload'?

// config/app.php
        'providers' => [
         ...,
            App\Providers\RouteServiceProvider::class,
            // Our new package class
            MyVendor\Contactform\ContactFormServiceProvider::class,
        ],

Please enlighten me...

Thanks!

0 likes
1 reply
D9705996's avatar

psr-4 is not a laravel thing its a php thing. The link below gives good detail but essentially your mapping a namespace to a folder in your filesystem

https://getcomposer.org/doc/04-schema.md#psr-4

Each package, includinglaravel, uses this to ensure your classes can be found in the filesystem.

For you service provider you are now telling laravel the namespace of the provider to load... the autoloader then translates that to the physical file.

A good example is that laravel had the App namespace mapped to the app folder (notice upper/lowercase)

1 like

Please or to participate in this conversation.