php-autoloading-y-psr-4-en-php

Autoloading and PSR-4 in PHP

  • 2 min

The autoloading mechanism loads a class when the code uses it, without writing a require for each file.

Remember those old index.php files that had 50 lines at the top doing require_once for every model, controller, and library?

// THE PAST (NIGHTMARE)
require_once 'includes/db.php';
require_once 'modelos/Usuario.php';
require_once 'modelos/Producto.php';
require_once 'controladores/HomeController.php';
// ... and so on for 50 more files
Copied!

This is unsustainable. If you move a file to another folder, you have to update all the require statements. If you have 100 classes but only use 1, you were loading all 100 into memory unnecessarily.

Autoloading solves this. It’s a system that says: “Don’t load anything at the beginning. Wait until the code requests a class (e.g., new Usuario) and, at that precise moment, find the file and load it automatically.”

What is PSR-4?

For Autoloading to work, we need a clear rule that tells PHP where to find the files.

PSR-4 is that standard rule. It establishes a direct correspondence between your Namespace and your Folder Structure.

If your class is called App\Models\User, PHP will automatically look for the file in the src/Models/User.php folder (assuming App points to src).

Configuring Composer for PSR-4

You don’t have to write the autoload function by hand. Composer does it for you. You just need to tell it in the composer.json file what your main folder is.

Suppose your code is in the src/ folder and you want to use the root namespace MyApp.

In your composer.json:

{
    "autoload": {
        "psr-4": {
            "MyApp\\": "src/"
        }
    }
}
Copied!

(Note the double backslashes \\. They are necessary because in JSON the backslash is an escape character).

Activating the autoload

Once you have modified the JSON, you must notify Composer to update its internal maps. Run this in the terminal:

composer dump-autoload
Copied!

The final result

Now, in your main file (e.g., index.php), you only need a single line of code to load your entire project, including any external libraries you downloaded.

File: public/index.php

<?php
// This line activates Composer's autoloader
require __DIR__ . '/../vendor/autoload.php';

use MyApp\Models\User;
use Monolog\Logger; // An external library installed via Composer

// It works! PHP detects that you are using "User", looks in src/Models/User.php and loads it.
$user = new User();

// It also works! It looks for the Monolog library in the vendor folder.
$log = new Logger('name');
Copied!