Menu
Coddy logo textTech

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 icon

Challenge

Easy

Let'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 a Logger class in the App\Services namespace. It should have a public $name property, a constructor that accepts and sets the name, and a log($message) method that returns "[name] logged: [message]".
  • src/Services/Mailer.php — Define a Mailer class in the App\Services namespace. It should have a public $sender property, a constructor that accepts and sets the sender, and a send($to) method that returns "Mail from [sender] to [to]".
  • main.php — Create a PSR-4 autoloader using spl_autoload_register that maps the App\ namespace prefix to the src/ directory. The autoloader should convert namespace separators to directory separators and append .php to find the correct file. After registering the autoloader, use the use keyword to import both classes, then create a Logger with name "FileLogger" and a Mailer with sender "admin@site.com". Print the result of calling log("System started") on the logger and send("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")
?>
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming