PHP
PSR-4 autoloading
Learn to write an autoloader that maps namespaces to file paths with PSR-4.
What is PSR-4?
PSR-4 is an autoloading standard that maps a namespace to a file path. The App\Models\User class is looked up in src/Models/User.php. This way you do not write a require for every class.
With spl_autoload_register() you register an autoloader function. PHP runs it when a missing class is referenced; the function loads the file and the class becomes ready to use.
The PSR-4 mapping method
In PSR-4 each \ becomes a directory separator and the vendor prefix maps to the base directory. For example, with prefix App and base src/: App\Models\User → src/Models/User.php.
The autoloader does: 1) strip the prefix, 2) turn the remaining \ into /, 3) prepend the base directory, 4) append the .php extension, 5) require the file.
Exercise Write a PSR-4 autoloader
Write a classToFile(string $class): string function: strip the App\ prefix, turn the remaining \ into /, prepend src/ and append .php. Then register it with spl_autoload_register and print the file path for App\Models\User.
Show example solution
string { $prefix = "App\\"; $base = "src/"; $relative = str_replace($prefix, "", $class); $relative = str_replace("\\", "/", $relative); return $base . $relative . ".php"; }. Register with spl_autoload_register. Print the path with echo classToFile("App\\Models\\User") . "\n";.
Example solution:
<?php
// PSR-4 path computation function
function classToFile(string $class): string {
$prefix = "App\\";
$base = "src/";
$relative = str_replace($prefix, "", $class);
$relative = str_replace("\\", "/", $relative);
return $base . $relative . ".php";
}
// Register it with spl_autoload_register
spl_autoload_register(function ($class) {
$file = classToFile($class);
require $file;
});
// Print the file path for App\Models\User
echo classToFile("App\\Models\\User") . "\n";
Test yourself
-
What does spl_autoload_register do?
- It deletes a class from memory
- It opens a database connection
- It registers an autoload function
- It throws an error
Show answer
It registers an autoload function — Correct. spl_autoload_register registers an autoload function.
-
Match the PSR-4 concepts
- App\Models\User
- src/Models/User.php
- spl_autoload_register
- Registers autoloader
- \
- Becomes directory separator
- vendor prefix
- Root name like App
-
Complete the str_replace call
<?php
$replacements = ["App\\" => "", "\\" => "/"];
$class = "App\\Models\\User";
$relative = ____(array_keys($replacements), array_values($replacements), $class);
echo $relative;
Show answer
<?php
$replacements = ["App\\" => "", "\\" => "/"];
$class = "App\\Models\\User";
$relative = str_replace(array_keys($replacements), array_values($replacements), $class);
echo $relative;
Next lesson: Summary - Namespaces