PSR-4 Autoloading Standard
Part of the Object Oriented Programming section of Coddy's PHP journey — lesson 12 of 91.
PSR-4 is a standard that defines how PHP classes should be automatically loaded based on their namespace and file location. Instead of manually including each class file, PSR-4 lets PHP find and load classes automatically when you use them.
The core rule is simple: the namespace must match the directory structure. If you have a class App\Models\User, the file should be located at App/Models/User.php.
<?php
// File: src/Models/User.php
namespace App\Models;
class User {
public $name;
public function __construct($name) {
$this->name = $name;
}
}
You can write a simple autoloader function that follows PSR-4 rules:
<?php
// File: autoload.php
spl_autoload_register(function ($class) {
$prefix = 'App\\';
$baseDir = __DIR__ . '/src/';
// Check if class uses our namespace prefix
if (strpos($class, $prefix) === 0) {
$relativeClass = substr($class, strlen($prefix));
$file = $baseDir . str_replace('\\', '/', $relativeClass) . '.php';
if (file_exists($file)) {
require $file;
}
}
});
The spl_autoload_register function tells PHP to call your function whenever it encounters an unknown class. The function converts the namespace to a file path and loads it.
Key Point: PSR-4 creates a predictable mapping between namespaces and file paths. When you see App\Models\User, you immediately know the file is at src/Models/User.php. This convention makes projects easier to navigate and maintain.
Challenge
EasyLet's build a simple PSR-4 autoloading system that automatically loads classes based on their namespace and file location.
You'll create a project with three files that demonstrate how PSR-4 maps namespaces to directory paths:
src/Services/Logger.php— Define aLoggerclass in theApp\Servicesnamespace. It should have apublic $nameproperty, a constructor that accepts and sets the name, and alog($message)method that returns"[name] logged: [message]".src/Services/Mailer.php— Define aMailerclass in theApp\Servicesnamespace. It should have apublic $senderproperty, a constructor that accepts and sets the sender, and asend($to)method that returns"Mail from [sender] to [to]".main.php— Create a PSR-4 autoloader usingspl_autoload_registerthat maps theApp\namespace prefix to thesrc/directory. The autoloader should convert namespace separators to directory separators and append.phpto find the correct file. After registering the autoloader, use theusekeyword to import both classes, then create aLoggerwith name"FileLogger"and aMailerwith sender"admin@site.com". Print the result of callinglog("System started")on the logger andsend("user@example.com")on the mailer (each on its own line).
The key insight is that your autoloader function receives the fully qualified class name (like App\Services\Logger) and must convert it to a file path (src/Services/Logger.php). Use strpos to check if the class starts with your namespace prefix, substr to get the relative class name, and str_replace to convert backslashes to forward slashes.
Cheat sheet
PSR-4 is a standard that defines how PHP classes should be automatically loaded based on their namespace and file location. The namespace must match the directory structure.
Example class structure:
<?php
// File: src/Models/User.php
namespace App\Models;
class User {
public $name;
public function __construct($name) {
$this->name = $name;
}
}
PSR-4 autoloader using spl_autoload_register:
<?php
spl_autoload_register(function ($class) {
$prefix = 'App\\';
$baseDir = __DIR__ . '/src/';
// Check if class uses our namespace prefix
if (strpos($class, $prefix) === 0) {
$relativeClass = substr($class, strlen($prefix));
$file = $baseDir . str_replace('\\', '/', $relativeClass) . '.php';
if (file_exists($file)) {
require $file;
}
}
});
The autoloader converts namespace separators (\) to directory separators (/) and appends .php to find the correct file. For example, App\Models\User maps to src/Models/User.php.
Try it yourself
<?php
// PSR-4 Autoloader Implementation
// TODO: Register an autoloader using spl_autoload_register
// The autoloader should:
// 1. Check if the class starts with 'App\' namespace prefix
// 2. Remove the 'App\' prefix to get the relative class name
// 3. Convert namespace separators (\) to directory separators (/)
// 4. Prepend 'src/' and append '.php' to build the file path
// 5. Require the file if it exists
spl_autoload_register(function ($class) {
// TODO: Define the namespace prefix and base directory
// TODO: Check if the class uses the namespace prefix (use strpos)
// TODO: Get the relative class name (use substr)
// TODO: Build the file path by replacing \ with / (use str_replace)
// TODO: Require the file if it exists
});
// TODO: Use the 'use' keyword to import Logger and Mailer classes
// TODO: Create a Logger instance with name "FileLogger"
// TODO: Create a Mailer instance with sender "admin@site.com"
// TODO: Print the result of log("System started")
// TODO: Print the result of send("user@example.com")
?>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe $this KeywordMethodsPropertiesConstructor (__construct)Destructor (__destruct)Recap - Simple Calculator4Inheritance
Basic InheritanceThe parent:: KeywordMethod OverridingThe final KeywordAbstract ClassesRecap - Employee Hierarchy7Encapsulation
Public, Protected, PrivateAccess Modifiers in DepthGetters and SettersInformation HidingConstructor Promotion (8.0)Recap - Student Records System2Namespaces & Autoloading
Introduction to NamespacesThe use KeywordPSR-4 Autoloading StandardComposer AutoloaderRecap - Organized Project5Interfaces & Contracts
Introduction to InterfacesImplementing InterfacesMultiple Interface ImplementInterface vs Abstract ClassType Hinting with InterfacesRecap - Shape Calculator8Magic Methods
Magic Methods Introduction__toString & __debugInfo__get, __set, __isset, __unset__call & __callStatic__clone & Object Cloning__serialize & __unserializeRecap - Custom Collection11Type System & Error Handling
Type DeclarationsNullable TypesUnion & Intersection TypesException ClassesCustom Exception HierarchyTry, Catch, FinallyRecap - Form Validator14Project: Library Management
Project OverviewBook and User Classes3Class Properties
Instance vs Static PropertiesConstants in ClassesStatic Methods & PropertiesPrivate & Protected PropertiesReadonly Properties (PHP 8.1)Recap - Bank Account Manager6Polymorphism
Method Overriding RevisitedPolymorphism via InterfacesType Hinting & Union TypesLate Static BindingRecap - Payment Processor9Traits
Introduction to TraitsUsing Multiple TraitsTrait Conflict ResolutionAbstract Methods in TraitsTraits vs Inheritance12Design Patterns Part 1
Intro to Design PatternsSingleton PatternFactory PatternObserver PatternStrategy Pattern