Namespaces & Autoloading — PHP

namespace App\Models; on a file's first line gives its class a full name (App\Models\Menu), so a same-named class from a library (code written by someone…

The app of Mrs. Tini's Stall keeps growing. Each class moves into a file of its own, and two classes with the same name start to clash. The top of every file also fills up with require lines (a require loads another PHP file), written one by one.

A namespace gives each class a full name, and autoloading lets PHP find that class's file by itself, with no require for each one. It's like a postal address: there are plenty of streets called "Jasmine Street", so a full address names the city. "Jasmine Street, Bristol" is not "Jasmine Street, Leeds". The street name is the class name, such as Menu, and the namespace is the city. PSR-4 is like the post office rule that turns a full address into the shelf where the letter is kept. From a class's full name, PHP knows the folder that holds its file.

Namespaces: a full name for a class

The stall's website uses a library (ready-made code written by someone else) for deliveries, and that library also has a Menu class. Without namespaces, two classes with the same name can't be used together. PHP stops with:

Fatal error: Cannot redeclare class Menu (previously declared in /var/www/stall/src/Models/Menu.php:2) in /var/www/stall/vendor/courier/api/src/Menu.php on line 2

With namespaces, every file names its "city" on the first line after <?php:

<?php
// src/Models/Menu.php
namespace App\Models;

class Menu
{
    public function __construct(public string $name, public int $price) {}
}

use: calling it by its short name

Other files can use that class. This is a Till class in the namespace App\Services, which uses Menu:

<?php
// src/Services/Till.php
namespace App\Services;

use App\Models\Menu;

class Till
{
    public function total(Menu $menu, int $quantity): int
    {
        return $menu->price * $quantity;
    }
}
Fatal error: Uncaught TypeError: App\Services\Till::total(): Argument #1 ($menu) must be of type App\Services\Menu, App\Models\Menu given

PSR-4: namespaces become folders

PSR-4 is the standard that maps a class name to the location of its file. The rule is written in composer.json, the settings file for Composer (the program that installs PHP libraries):

{
    "autoload": {
        "psr-4": {
            "App\\": "src/"
        }
    }
}
Class name Prefix App\ replaced by src/ File
App\Models\Menu src/ + Models\Menu src/Models/Menu.php
App\Services\Till src/ + Services\Till src/Services/Till.php

Then run Composer in the terminal:

$ composer dump-autoload
Generating autoload files
Generated autoload files

Then index.php, the file that runs first, loads the autoloader:

<?php
require __DIR__ . "/vendor/autoload.php";

use App\Models\Menu;
use App\Services\Till;

$rice = new Menu("Fried Rice", 15);
echo (new Till())->total($rice, 2) . "\n"; // 30

If the file isn't at that path, or vendor/autoload.php was never required, the result is the same:

Fatal error: Uncaught Error: Class "App\Models\Menu" not found in /var/www/stall/index.php:7

💡 When composer dump-autoload is needed

⚠️ Why can't PHP find the class?

TL;DR: namespace App\Models; on a file's first line gives its class a full name (App\Models\Menu), so a same-named class from a library (code written by someone else) doesn't clash. use App\Models\Menu; makes the short name Menu point there. Without use, PHP looks in the file's own namespace. as gives an alias (another name), and inside a namespace, PHP's built-in classes are written with a backslash in front, such as \DateTime. Autoloading lets PHP load class files by itself, with no require for each one. PSR-4 maps namespaces to folders: with "App\\": "src/" in composer.json, App\Models\Menu lives in src/Models/Menu.php. Run composer dump-autoload after changing the autoload section, and require "vendor/autoload.php" only once. When the file's location doesn't match, PHP stops with Class "App\Models\Menu" not found.

⚡ Namespace: a full name for a class

Write:

<?php
// src/Models/Menu.php
namespace App\Models;

class Menu
{
    public function __construct(public string $name, public int $price) {}
}

Meaning: A namespace gives a class a full name, like the city in a postal address. The line namespace App\Models; makes this class's full name App\Models\Menu. So it doesn't clash with a Menu class from a library (code written by someone else). The separator is a backslash \, and the namespace line must be the first statement in the file.

⚡ use: call it by its short name

Guess first: a file starts with namespace App\Services;, then uses the Menu class from App\Models with no use line. What is Menu read as in that file?

App\Services\Menu. A short name (the name without a namespace) is looked up in the file's own namespace. So a parameter of type Menu refuses an App\Models\Menu object with a TypeError.

Meaning: use App\Models\Menu; tells PHP: in this file, Menu means App\Models\Menu. So you only need to write the short name.

⚡ PSR-4: namespaces become folders

Write:

{
    "autoload": {
        "psr-4": {
            "App\\": "src/"
        }
    }
}

Meaning: This PSR-4 rule in composer.json replaces the prefix App\ with the folder src/. So App\Models\Menu lives in src/Models/Menu.php. One file holds one class with one namespace. After composer dump-autoload runs in the terminal, the file vendor/autoload.php (the autoloader) loads class files by itself when a class is used. You require that file only once, in the file that runs first.

What you will learn