Namespaces and Composer
Organizing code with namespaces and managing third-party packages with Composer.
2 min read
As a PHP codebase grows past a handful of files, two problems show up quickly: class names collide, and you need a reliable way to pull in code other people wrote. Namespaces and Composer solve those, respectively.
Why namespaces exist
<?php
// File: app/Models/User.php
namespace App\Models;
class User {
public function __construct(public string $name) {}
}<?php
// File: app/Services/User.php
namespace App\Services;
class User {
// an entirely different, unrelated "User" concept
}Without namespaces, two classes both named User in the same project would collide — PHP wouldn't know which one you meant. namespace App\Models; at the top of a file scopes every class, function, and constant declared there under that namespace, so both User classes above can coexist as App\Models\User and App\Services\User.
Using a namespaced class
<?php
use App\Models\User;
$user = new User("Amara");use App\Models\User; imports a specific namespaced class so it can be referred to by its short name (User) for the rest of the file, instead of writing the fully-qualified \App\Models\User every time.
Autoloading: how PHP finds the file for a class
{
"autoload": {
"psr-4": {
"App\\": "app/"
}
}
}Modern PHP doesn't require manually require-ing every file — Composer's autoloader maps a namespace prefix to a directory (following the PSR-4 standard shown above), so referencing App\Models\User automatically loads app/Models/User.php the first time it's used, with zero manual require statements anywhere in your code.
Composer: installing and managing packages
composer require guzzlehttp/guzzle{
"require": {
"guzzlehttp/guzzle": "^7.0"
}
}composer require downloads a package (here, a popular HTTP client library) into a vendor/ directory and records it in composer.json, alongside the version constraint (^7.0 means "7.x, but not 8.0 or later"). Anyone else on the project runs composer install to get the exact same dependencies.
Using an installed package
<?php
require "vendor/autoload.php";
use GuzzleHttp\Client;
$client = new Client();
$response = $client->get("https://api.example.com/users");vendor/autoload.php is Composer's generated autoloader — including it once (usually at your application's entry point) makes every installed package's classes available via use, exactly the same way as your own namespaced classes. Every framework covered later in this course (Laravel, Symfony) is itself installed and loaded this exact way.
Test what you just learned
4 quick questions. Get all of them right to unlock the next lesson.
You can take the quiz without an account — logging in just lets your result count toward your progress.