Skip to content
intermediate Phase 6 · PHP Advanced

PHP Autoloading: PSR-4 and Magento's Mechanism

Master PSR-4 autoloading, spl_autoload_register, Composer autoloader, and Magento's autoloading mechanism.

45m
0 problems
Topic Progress 0%

Autoloading Basics

Why Autoloading?

Before autoloading, you had to manually include every file:

<?php
// OLD WAY - tedious and error-prone
require_once __DIR__ . '/Model/Product.php';
require_once __DIR__ . '/Helper/Data.php';
require_once __DIR__ . '/Controller/Index.php';

$product = new Product();

With autoloading, classes are loaded automatically when first used:

<?php
// NEW WAY - classes loaded automatically
$product = new Product(); // Autoloader finds and loads the file

spl_autoload_register

<?php
// Register a custom autoloader
spl_autoload_register(function (string $class) {
    // Convert namespace to file path
    // Vendor\Module\Product -> src/Product.php
    $file = __DIR__ . '/' . str_replace('\\', '/', $class) . '.php';

    if (file_exists($file)) {
        require_once $file;
    }
});

// Now this works without any require/include
$product = new Product();
// Autoloader loads: ./Product.php

How Autoloading Works

1. You use: $product = new Vendor\Module\Product();
2. PHP doesn't know this class yet
3. PHP calls each registered autoloader
4. Autoloader receives: 'Vendor\Module\Product'
5. Autoloader converts to file path:
   Vendor\Module\Product -> Vendor/Module/Product.php
6. Autoloader checks if file exists
7. If yes, require_once the file
8. Class is now available
9. PHP creates the object

Multiple Autoloaders

<?php
// Register multiple autoloaders
spl_autoload_register(function ($class) {
    // Custom autoloader for app classes
    $file = __DIR__ . '/app/' . str_replace('\\', '/', $class) . '.php';
    if (file_exists($file)) {
        require_once $file;
    }
});

spl_autoload_register(function ($class) {
    // Custom autoloader for lib classes
    $file = __DIR__ . '/lib/' . str_replace('\\', '/', $class) . '.php';
    if (file_exists($file)) {
        require_once $file;
    }
});

// PHP tries each autoloader in order until one loads the class

Key Takeaway

Autoloading automatically loads class files when they're first used. spl_autoload_register() adds custom autoloaders. Composer generates an optimized autoloader for you.

PSR-4 Autoloading Standard

PSR-4 Directory Mapping

PSR-4 maps namespaces to directories:

Namespace: Vendor\Module\Model\
Directory: app/code/Vendor/Module/Model/

Class: Vendor\Module\Model\Product
File:  app/code/Vendor/Module/Model/Product.php

Class: Vendor\Module\Model\ResourceModel\Product
File:  app/code/Vendor/Module/Model/ResourceModel/Product.php

composer.json PSR-4 Configuration

{
    "autoload": {
        "psr-4": {
            "Vendor\\Module\\": "app/code/Vendor/Module/"
        }
    }
}

Mapping:

  • Prefix: Vendor\Module\
  • Directory: app/code/Vendor/Module/
  • The prefix is removed from the class name to get the relative path
Vendor\Module\Model\Product
  -> Remove prefix: Model\Product
  -> Replace \ with /: Model/Product.php
  -> Prepend directory: app/code/Vendor/Module/Model/Product.php

Multiple Namespace Prefixes

{
    "autoload": {
        "psr-4": {
            "Vendor\\Module\\": "app/code/Vendor/Module/",
            "Vendor\\Module\\Test\\": "app/code/Vendor/Module/Test/"
        }
    }
}

Magento's PSR-4 Configuration

{
    "autoload": {
        "psr-4": {
            "Magento\\\\": "app/code/Magento/",
            "": "app/code/"
        }
    }
}

The empty string prefix "" means: any class without a registered prefix will be looked up in app/code/.

Vendor\Module\Product
  -> No prefix matches (Magento\\\\ doesn't match)
  -> Use empty prefix: ''
  -> Directory: app/code/
  -> File: app/code/Vendor/Module/Product.php

PSR-4 Rules

1. Namespace prefix maps to base directory
2. Namespace segments map to subdirectories
3. Class name maps to filename (case-sensitive)
4. Underscores in class names have NO special meaning
5. One class per file
6. Filename must match class name exactly

Key Takeaway

PSR-4 maps namespaces to directories. The namespace prefix is stripped, and the remainder becomes the file path. Composer generates an optimized autoloader based on your PSR-4 configuration.

Magento's Autoloading Mechanism

Magento's Autoloading Stack

Magento uses multiple autoloaders:

1. Composer autoloader (vendor/autoload.php)
   - PSR-4 for vendor packages
   - Classmap for performance

2. Magento generated autoloader
   - Generated by setup:di:compile
   - Maps generated classes (proxies, factories)

3. Magento fallback autoloader
   - Handles Magento-specific paths
   - Falls back to theme files

Magento Entry Point

<?php
// pub/index.php
use Magento\Framework\App\Bootstrap;

require __DIR__ . '/../app/bootstrap.php';

// bootstrap.php loads:
// 1. vendor/autoload.php (Composer autoloader)
// 2. Magento framework classes
// 3. Module registrations

$bootstrap = Bootstrap::create(BP, $_SERVER);
$application = $bootstrap->createApplication(
    \Magento\Framework\App\Http::class
);
$application->run();

Generated Classes

<?php
// After setup:di:compile, Magento generates:

// Factory classes
app/code/Vendor/Module/Model/ProductFactory.php
// Generated from: Product class
// Used to create new Product instances

// Proxy classes
app/code/Vendor/Module/Model/Product/Proxy.php
// Lazy-loading proxy for dependency injection

// Interceptor classes
app/code/Vendor/Module/Model/Product/Interceptor.php
// Plugin system - wraps methods for before/after/around

Magento Module File Structure

app/code/Vendor/Module/
├── registration.php              # Module registration
├── etc/
│   ├── module.xml               # Module declaration
│   ├── di.xml                   # Dependency injection config
│   ├── frontend/routes.xml      # Frontend routes
│   ├── adminhtml/routes.xml     # Admin routes
│   └── crontab.xml             # Cron jobs
├── Block/                       # Block classes
│   └── Product/
│       └── View.php
├── Controller/                  # Controllers
│   └── Index/
│       └── Index.php
├── Model/                       # Models
│   ├── Product.php
│   ├── ProductRepository.php
│   └── ResourceModel/
│       ├── Product.php
│       └── Product/
│           └── Collection.php
├── Helper/                      # Helpers
│   └── Data.php
├── Observer/                    # Event observers
│   └── ProductSave.php
├── Plugin/                      # Plugins
│   └── ProductPlugin.php
├── view/                        # Templates and assets
│   ├── frontend/
│   │   ├── templates/
│   │   ├── web/css/
│   │   └── web/js/
│   └── adminhtml/
├── Setup/                       # Install/upgrade scripts
│   └── InstallSchema.php
├── Api/                         # API interfaces
│   └── Data/
│       └── ProductInterface.php
└── Test/                        # Tests
    ├── Unit/
    └── Integration/

Debugging Autoloading

<?php
// Check what autoloaders are registered
print_r(spl_autoload_functions());

// Check if a class can be loaded
class_exists('Vendor\Module\Model\Product');

// Check where a class is loaded from
$reflection = new ReflectionClass('Vendor\Module\Model\Product');
echo $reflection->getFileName();

// Composer's classmap
// Run: composer dump-autoload -v
// Shows all classes and their file paths

Key Takeaway

Magento uses Composer's autoloader as the primary mechanism, supplemented by generated classes (factories, proxies, interceptors). The autoloading chain handles everything from vendor packages to theme templates.

Quiz

1. What does spl_autoload_register do?

Question 1 options

2. In PSR-4, how is Vendor\Module\Model\Product mapped to a file?

Question 2 options

3. What does composer dump-autoload do?

Question 3 options

4. What files does Magento generate after setup:di:compile?

Question 4 options

5. What is the purpose of registration.php in a Magento module?

Question 5 options

Flashcards

Question

What is autoloading in PHP?

Answer

Automatic class loading when a class is first used. No need for require/include. PHP calls registered autoloaders to find and load class files.

Question

What does spl_autoload_register do?

Answer

Registers a function as an autoloader. When PHP encounters an unknown class, it calls this function to find and load the class file.

Question

How does PSR-4 map namespaces to files?

Answer

Namespace prefix maps to base directory. Vendor\Module\Product with prefix Vendor\\Module\\ maps to Product.php in the module directory.

Question

What does composer dump-autoload generate?

Answer

Optimized autoloader files: classmap (fast class lookup), psr4 (namespace mapping), files (included files), and static (optimized for production).

Question

What files does Magento generate after setup:di:compile?

Answer

Factory classes (create instances), Proxy classes (lazy loading), Interceptor classes (plugin system). Stored in generated/ directory.

Question

What is the Magento entry point for autoloading?

Answer

pub/index.php requires app/bootstrap.php, which loads vendor/autoload.php (Composer) and initializes the Magento application.

Question

What is a classmap in Composer autoloading?

Answer

A pre-computed map of class names to file paths. Faster than PSR-4 because it doesn't need to convert namespaces to paths at runtime.

Question

What does registration.php do in a Magento module?

Answer

Calls ComponentRegistrar::register() to register the module with Magento. Tells Magento the module name and location.

Revision Notes

Key Takeaways

  • 1. Autoloading loads class files automatically when first used
  • 2. spl_autoload_register() adds custom autoloaders to the stack
  • 3. PSR-4 maps namespace prefixes to directories
  • 4. Composer generates optimized autoloaders (classmap, PSR-4)
  • 5. Magento uses Composer autoloader + generated classes
  • 6. setup:di:compile generates factories, proxies, and interceptors
  • 7. registration.php registers modules with Magento

Interview Tips

  • Explain how autoloading works step by step
  • Describe PSR-4 namespace-to-directory mapping
  • Know the difference between classmap and PSR-4 autoloading
  • Explain what Magento generates during compilation
  • Describe the Magento bootstrap process

Cheat Sheet

PHP Autoloading Cheat Sheet

spl_autoload_register:

spl_autoload_register(function ($class) {
    $file = __DIR__ . '/' . str_replace('\\', '/', $class) . '.php';
    if (file_exists($file)) require_once $file;
});

PSR-4 Mapping:
Vendor\Module\Product -> Vendor/Module/Product.php

Composer PSR-4:

"autoload": {
    "psr-4": { "Vendor\\Module\\": "src/" }
}

Magento Generated:

  • Factory: Creates new instances
  • Proxy: Lazy loading wrapper
  • Interceptor: Plugin system hooks

Commands:
composer dump-autoload # Regenerate autoloader
bin/magento setup:di:compile # Generate Magento classes