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) {}
}
namespace App\Models;makes the full name of the class in this fileApp\Models\Menu. The library'sMenuclass has its own namespace, so its full name isCourier\Api\Menu. Those two full names are different, so they no longer clash.- The separator is a backslash
\, not a dot or a forward slash. - The
namespaceline must be the first statement in the file. With anechoabove it, the result is:Namespace declaration statement has to be the very first statement or after any declare call in the script. Menu::classholds the full name as a string:"App\Models\Menu".
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;
}
}
- Inside
namespace App\Services, the short nameMenu(the name without a namespace) is looked up in that namespace itself:App\Services\Menu. use App\Models\Menu;tells PHP: in this file,MenumeansApp\Models\Menu.- Without that
useline, the parameter typeMenuis read asApp\Services\Menu. Callingtotal()with anApp\Models\Menuobject gives:
Fatal error: Uncaught TypeError: App\Services\Till::total(): Argument #1 ($menu) must be of type App\Services\Menu, App\Models\Menu given
- Two classes with the same short name in one file? Give one of them an alias (another name) with
as:use Courier\Api\Menu as CourierMenu;. Without the alias, the result isCannot use Courier\Api\Menu as Menu because the name is already in use. - PHP's built-in classes, such as
DateTime(for dates and times), are in the global namespace, which is outside every namespace. Inside a namespace,new DateTime()is looked up asApp\Services\DateTimeand fails withClass "App\Services\DateTime" not found. Writenew \DateTime()(a backslash in front means "from the global namespace") oruse DateTime;.
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
"App\\"is written with two backslashes, because in JSON one backslash must be written twice. It still means the prefixApp\.composer dump-autoloadwrites a map of thecomposer.jsonrules into thevendor/composer/folder, then createsvendor/autoload.php. That file is the autoloader.require __DIR__ . "/vendor/autoload.php";is needed once, in the file that runs first. (__DIR__holds the folder this file is in.) Whenever a class that isn't loaded yet is used, for examplenew Menu(...), the autoloader calculates its path (the file's location) with the rule in the table, thenrequires that file.- The rules: one file holds one class, the file name matches the class name exactly (
Menu.php), and the folder names match the namespace parts exactly (Models, notModel). On a Linux server, letter case in folder names counts too.
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
- It's required after changing the
autoloadsection ofcomposer.json, for example fromsrc/toapp/. Until you runcomposer dump-autoload, the autoloader still uses the old map. - A new class file in a folder PSR-4 already maps (for example
src/Models/Order.php) is found right away withoutcomposer dump-autoload: its path is calculated when the class is used. composer dump-autoload -obuilds a list of every class at once (a classmap), a little faster for production servers (the servers real visitors use).- Laravel (a PHP framework) uses the same rule:
"App\\": "app/", soApp\Models\Userlives inapp/Models/User.php.
⚠️ Why can't PHP find the class?
- Forgetting
use. A short name is looked up in the file's own namespace, soMenuinApp\ServicesbecomesApp\Services\Menu. - A folder or file name that doesn't match the namespace.
src/Model/Menu.phpforApp\Models\Menuis never found:Class "App\Models\Menu" not found. - Forgetting
require "vendor/autoload.php". Without it there's no autoloader at all. - Several namespaces in one file. PHP does allow more than one
namespaceline in a file, but PSR-4 requires one class with one namespace per file. Split them into files of their own.
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.