Composer, autoloading and the PSRs
Laravel Saga · Season 0 · Episode 05
Try a quick test: create a new Laravel project and count how many PHP files there are inside the vendor/ folder. There are thousands, from dozens of packages written by people who have never met. And yet everything works together. You never write a single require.
That's not luck. It's the result of two things we'll study today: Composer, which manages dependencies and loads classes automatically, and the PSRs, standards that make libraries by different authors speak the same language.
What life was like before Composer
If you started programming in PHP after 2012 just like me, you may never have been through this. Reusing code meant downloading a .zip, copying it into a lib/ folder and filling your files with require_once:
phprequire_once 'lib/Mailer/Mailer.php';
require_once 'lib/Mailer/SmtpTransport.php';
require_once 'lib/Http/Client.php';
require_once 'lib/Http/Response.php';
// ... and a hundred more lines just like theseUpdating a library was manual work. If two libraries depended on different versions of a third one, good luck. And every framework was an island, with its own solutions for everything.
Composer: the dependency manager
Composer solves three problems at once:
- It installs packages and those packages' dependencies.
- It resolves versions that are compatible across all of them.
- It loads classes automatically, the famous autoload.
Packages come from Packagist (packagist.org), the public repository of the PHP ecosystem.
The composer.json
Everything starts with this file. Take a look at a typical example:
json{
"name": "myblog/app",
"type": "project",
"require": {
"php": "^8.3",
"laravel/framework": "^13.0",
"guzzlehttp/guzzle": "^7.9"
},
"require-dev": {
"pestphp/pest": "^4.0",
"laravel/pint": "^1.20"
},
"autoload": {
"psr-4": {
"App\\": "app/",
"Database\\Factories\\": "database/factories/",
"Database\\Seeders\\": "database/seeders/"
}
},
"scripts": {
"test": "php artisan test"
}
}Each section has a very clear role:
require: what the application needs to run.require-dev: development-only tools, such as tests and the formatter. In production, you usecomposer install --no-devand they're left out.autoload: how to find your project's classes. We'll come back to this shortly.scripts: shortcuts for commands, such ascomposer test.
Understanding version constraints
Packages follow Semantic Versioning, in the MAJOR.MINOR.PATCH format:
- MAJOR changes when something breaks compatibility (Laravel 12 to 13).
- MINOR adds features without breaking anything (13.1 to 13.2).
- PATCH fixes bugs (13.2.0 to 13.2.1).
And composer.json uses a few symbols to say which versions you accept:
| Constraint | Accepts | When to use it |
|---|---|---|
^13.0 | >=13.0.0 <14.0.0 | The most common: accepts anything that doesn't break |
~13.2 | >=13.2.0 <14.0.0 | Similar to ^ when there are two numbers |
~13.2.1 | >=13.2.1 <13.3.0 | Fixes only |
13.2.1 | Exactly that one | Rarely a good idea |
The composer.lock: the exact snapshot
Here's a very common confusion, so let me be blunt. composer.json says what is acceptable. composer.lock records exactly what was installed, with the version and hash of every package.
| Command | What it does |
|---|---|
composer install | Installs exactly what's in the .lock |
composer update | Resolves the versions again, respecting the .json, and rewrites the .lock |
composer require package | Adds a package and updates both files |
The golden rule is: commit composer.lock to Git and use composer install in production and in CI. That way, your machine, your colleague's and the server all run exactly the same versions. No more "works on my machine".
On your machine
composer update resolves the versions again within the .json ranges, rewrites the .lock and installs. You commit the new .lock.
CI and production
composer install doesn't even look at the ranges: it installs exactly the versions and hashes recorded in the .lock.
composer install --no-dev
Autoload: never require again
Now on to autoloading, which is where the magic (that isn't magic) happens. It relies on a native PHP function, spl_autoload_register(). It tells PHP something like: "when someone uses a class that hasn't been loaded yet, call this function to find it".
So you can understand the principle, here's a hand-written autoloader:
phpspl_autoload_register(function (string $class) {
$prefix = 'App\\';
$baseDir = __DIR__ . '/app/';
if (! str_starts_with($class, $prefix)) {
return;
}
$relative = substr($class, strlen($prefix));
$file = $baseDir . str_replace('\\', '/', $relative) . '.php';
if (file_exists($file)) {
require $file;
}
});
new App\Services\PaymentService(); // loads app/Services/PaymentService.phpSimple, right? Composer generates a much more complete and optimised autoloader, and you only need one line to switch it on. In fact, it's exactly the line that appears in Laravel's public/index.php:
phprequire __DIR__ . '/../vendor/autoload.php';A few commands worth keeping close at hand:
bashcomposer dump-autoload # regenerates the autoload after changing composer.json
composer dump-autoload -o # optimised version for production (class map)
composer show # installed packages
composer why guzzlehttp/guzzle # who depends on this package?
composer outdated # what has a new version available?
composer audit # known vulnerabilities in the dependenciescomposer audit, in particular, deserves a place in your routine. It warns you when a dependency has a known security flaw.
PHP-FIG and the PSRs
Now for the second half of the episode. Composer handles installation and loading. But how do you make sure a package written by one person works well with another written by someone else?
That's where PHP-FIG (Framework Interop Group) comes in, a group made up of representatives of several PHP frameworks and projects. It publishes the PSRs (PHP Standard Recommendations), standards that let code from different projects fit together.
The idea behind several PSRs is to define common interfaces. If your code depends on a PSR interface, and not on a specific library, you can swap the library without touching your code. Hold on to that sentence, because it will be the theme of the next two episodes.
The PSRs you need to know
PSR-1 and PSR-12 (coding style), which have since evolved into the PER Coding Style. They define things like class names in StudlyCase, methods in camelCase, 4-space indentation and where the braces go. Laravel Pint formats your code following a variation of this standard.
PSR-3 (Logger): a LoggerInterface with methods such as info(), error() and warning(). Laravel's logger implements this interface, so any library that accepts a PSR-3 logger accepts Laravel's logger.
PSR-4 (Autoload): the rule that ties namespaces to folders. It's exactly the one we configured in composer.json:
| Namespace | File |
|---|---|
App\Http\Controllers\PostController | app/Http/Controllers/PostController.php |
App\Models\Post | app/Models/Post.php |
That's why, in Laravel, a class's namespace has to match the folder it lives in. If you move a file and forget to adjust the namespace, you're rewarded with the famous Class not found.
PSR-7 (HTTP messages): interfaces for immutable Requests and Responses. Laravel internally uses Symfony's HttpFoundation, which doesn't follow PSR-7, but it can convert to and from PSR-7 when needed, through an official Symfony bridge.
PSR-11 (Container): a minimal interface for dependency injection containers, with just two methods, get($id) and has($id). Laravel's container implements this interface. We'll build a container in episode 07.
PSR-14 (Events): interfaces for dispatching events and registering whoever reacts to them.
PSR-15 (HTTP middleware): defines middleware as a layer that receives the request, can pass it on to the next handler and returns a response. One important detail: Laravel's middleware doesn't implement the PSR-15 interface (it uses a closure called $next), but the concept is exactly the same. Whoever understands PSR-15 already understands Laravel's middleware.
PSR-16 (Simple cache): get, set, delete and has methods. Laravel's cache implements this interface.
PSR-18 (HTTP client): an interface for HTTP clients. Guzzle, which Laravel's Http:: uses underneath, implements this interface.
Why this matters day to day
Look at this class:
phpuse Psr\Log\LoggerInterface;
class PaymentGateway
{
public function __construct(private LoggerInterface $logger) {}
public function charge(int $amount): void
{
$this->logger->info('Charging', ['amount' => $amount]);
}
}It works with Laravel's logger, with plain Monolog or with any other framework's logger. Why? Because it depends on a contract, not on a specific implementation. That's exactly the idea we'll dig into in the next episode.
The ecosystem that grows out of this
Thanks to Composer and the PSRs, Laravel doesn't need to reinvent everything. It relies on well-established components from other projects:
| Package | Used by Laravel for |
|---|---|
symfony/http-foundation | Request and Response |
symfony/routing | Route compilation |
symfony/console | Artisan commands |
symfony/mailer | Sending email |
nesbot/carbon | Dates |
league/flysystem | Filesystem (local, S3, FTP) |
monolog/monolog | Logs |
guzzlehttp/guzzle | HTTP client |
Want to see it with your own eyes? Run this command in a Laravel project:
bashcomposer show --tree laravel/frameworkYou'll see the whole dependency tree. And you'll realise that the framework is, to a large extent, a very elegant integration layer over excellent components. That doesn't diminish Laravel; quite the opposite, it shows it was built wisely.
What to take into the saga
- Composer installs packages, resolves versions and generates the autoload.
- Commit
composer.lockand usecomposer installin production. - PSR-4 ties namespaces to folders, which is why
App\Models\Postlives inapp/Models/Post.php. - The PSRs define common interfaces (logger, container, cache, HTTP) that make libraries interchangeable.
- Laravel relies on components from Symfony, the League and other projects.
Next episode
We've seen that depending on an interface, instead of a concrete class, makes code flexible. That idea didn't come out of nowhere: it comes from the principles of object orientation and, in particular, from SOLID.
In the next episode, we'll revisit object orientation and SOLID, but without dogs inheriting from animals. I'll use examples from real web applications, focusing on the concepts Laravel uses all the time. See you in episode 06.
References and further reading
Official documentation
- Composer documentation: installation, commands and
composer.json. - Versions and constraints in Composer: the meaning of
^,~and friends. - Autoload in composer.json: PSR-4, classmap and files.
- Semantic Versioning: the specification.
- Packagist: the public repository of PHP packages.
The PSRs
- PHP-FIG's list of PSRs: every accepted recommendation.
- PSR-4: Autoloader, PSR-11: Container and PSR-15: HTTP Middleware: the three most important for the saga.
- PER Coding Style: the evolution of PSR-12.
In Laravel
- Laravel contracts: the interfaces in
Illuminate\Contracts.