Autoloading Your Own Code
The earlier Autoloading page showed how
vendor/autoload.php automatically loads classes from packages you install. That same
autoloader can also load your own classes — the code you write for your
project — with zero manual include or require statements, using the
autoload section of composer.json.
The autoload Section and PSR-4
PSR-4 is a PHP standard that maps namespace prefixes to folders on disk. Composer understands PSR-4 natively: you tell it "this namespace prefix lives in this folder", and it generates the mapping code for you.
{
"autoload": {
"psr-4": {
"App\\": "src/"
}
}
}
This tells Composer: "any class inside the App namespace lives inside the src/
folder." Note that JSON requires a backslash to be written as two backslashes inside a string, so
"App\\" represents the single namespace separator App\.
A Worked Example
With the mapping above in place, a class named App\Greeter must live at
src/Greeter.php. The folder path after the namespace prefix mirrors the rest of the
namespace, and the file name matches the class name.
<?php
namespace App;
class Greeter
{
public function greet($name)
{
return "Hello, $name!";
}
}
Once vendor/autoload.php has been required, App\Greeter can be used anywhere
in the project with no manual require for src/Greeter.php at all.
<?php
require __DIR__ . '/vendor/autoload.php';
$greeter = new \App\Greeter();
echo $greeter->greet('World'); // Hello, World!
The Gotcha: Run composer dump-autoload
Composer generates the actual autoloader files once, based on whatever the autoload
section says at that moment. If you add the autoload block for the first time, change the
namespace mapping, or simply create a brand new class file, Composer doesn't notice automatically —
you have to tell it to regenerate the mapping.
composer dump-autoload
composer dump-autoload so Composer regenerates its internal class map to include the file
you just added.
You'll also see Composer run this step automatically after composer install or
composer require — but any time you edit the autoload section by hand,
or add files in a way Composer wouldn't otherwise notice, run it yourself to be safe.