In the last lesson you wrote an autoloader that maps App\Service\Greeter to src/Service/Greeter.php. If every project invented its own mapping, sharing code would be a mess. PSR-4 is the agreed standard.
PSR stands for PHP Standards Recommendation. They come from the PHP-FIG group. PSR-4 describes how a fully qualified class name maps to a file path.
The rule
- A namespace prefix is mapped to a base folder.
- The rest of the class name is turned into a path: each
\becomes/, and.phpis added.
| Prefix | Base folder |
|---|---|
App\ | src/ |
| Class | File |
|---|---|
App\Service\Greeter | src/Service/Greeter.php |
App\Model\User | src/Model/User.php |
App\Http\Controller\HomeController | src/Http/Controller/HomeController.php |
What you must do
- One class (or interface, trait, enum) per file.
- The file name equals the type name exactly, including capitals.
- The namespace in the file matches the folder path.
A file src/Service/Greeter.php must declare:
<?php
namespace App\Service;
class Greeter {}
A tiny PSR-4 autoloader
This shows how a PSR-4 mapper works.
<?php
function psr4Path(string $class, string $prefix, string $baseDir): ?string
{
if (!str_starts_with($class, $prefix)) {
return null;
}
$relative = substr($class, strlen($prefix));
return rtrim($baseDir, "/") . "/" . str_replace("\\", "/", $relative) . ".php";
}
echo psr4Path("App\\Service\\Greeter", "App\\", "src") . "\n";
var_dump(psr4Path("Vendor\\Thing", "App\\", "src"));
src/Service/Greeter.php
NULL
Several mappings
A project can map several prefixes:
| Prefix | Folder |
|---|---|
App\ | src/ |
Tests\ | tests/ |
Database\Seeders\ | database/seeders/ |
Why this standard matters
- Every Composer package follows it, so installing a package “just works”.
- Any tool or editor can find the file for a class name.
- You can move between projects and know where things are.
Telling Composer
You do not write the autoloader. You describe the mapping in composer.json, and Composer generates the code.
{
"autoload": {
"psr-4": {
"App\\": "src/"
}
}
}
The next chapter covers Composer, including this setting in PSR-4 Autoloading with Composer.
Other PSRs you will hear about
| PSR | Topic |
|---|---|
| PSR-1, PSR-12 | Coding style |
| PSR-3 | Logger interface |
| PSR-4 | Autoloading |
| PSR-7 | HTTP messages |
| PSR-11 | Container interface |
| PSR-15 | HTTP middleware |
You do not need to memorise them. They show up when you use libraries and frameworks.
Case matters on Linux
Greeter.php and greeter.php are different files on Linux but the same on Windows. A project that works on your Windows laptop can fail on a Linux server if the capitals differ. Always match the class name exactly.