Hello! Welcome to the final lesson in our module on Composer.
In our last session, we learned how to find, install, and update external packages using commands like composer require and composer install. This populated our vendor directory with powerful, third-party code. But a crucial question remains: how do we use these classes—and our own custom classes—without littering our code with require statements?
This lesson answers that question. We will explore one of the most powerful features of modern PHP development: autoloading. You'll learn how Composer can automatically load class files on-demand, following a community standard known as PSR-4.
By the end of this lesson, you will be able to configure and use a PSR-4 autoloader to automatically load class files, a fundamental skill for building organized, scalable PHP applications.
1. The Problem: Manual File Loading
Before autoloading became standard, developers had to manually include every file that contained a class they wanted to use.
Imagine a simple project structure:
project/
├── index.php
├── classes/
│ ├── User.php
│ └── Product.php
To use both the User and Product classes in index.php, you would have to write:
<?php
require 'classes/User.php';
require 'classes/Product.php';
$user = new User();
$product = new Product();
// ...
This might seem manageable with two classes, but in a real web application with hundreds of classes, it becomes a maintenance nightmare. Every time you need a new class, you have to add another require statement. Forgetting one results in a fatal error.
This video introduces the problem and sets the stage for the solution: autoloading.
Autoloading Classes in PHP: PSR-4 and Composer
This first segment from Dave Hollingworth's video on autoloading clearly demonstrates the issue with manual require statements and introduces the concept of automatically loading classes.
Watch from the beginning to 04:03. The first part (until 02:23) shows the problem with require. The second part (from 02:23 to 04:03) introduces PHP's built-in spl_autoload_register function, which is the mechanism that makes all autoloading possible.
As the video showed, PHP provides a function, spl_autoload_register(), that allows you to define a "handler" for when your code tries to use a class that hasn't been loaded yet. This is the core principle of autoloading: instead of loading everything upfront, we load files just-in-time.
2. PSR-4: The Autoloading Standard
While you could write your own custom autoloader function, the PHP community has created a standard to make this predictable and interoperable. This is where PSR-4 comes in.
PSR stands for "PHP Standard Recommendation," and the standards are developed by the PHP Framework Interop Group (PHP-FIG). PSR-4 is the modern standard for autoloading classes. It defines a simple rule: a class's namespace and name must map directly to a directory and file path.
Let's break down the key rules of PSR-4:
- Structure: A fully qualified class name looks like this:
\<VendorName>\(<SubNamespace>)*\<ClassName>. - Mapping: This class name is mapped to a file path.
- A base namespace prefix (e.g.,
App\) maps to a base directory (e.g.,src/). - The rest of the namespace corresponds to subdirectories within that base directory.
- The class name itself must match the file name (e.g.,
ClassName.php).
- A base namespace prefix (e.g.,
- Case-Sensitivity: The case of the namespace and class name must match the case of the directory and file names.
Here is a practical example:
| Component | Value | Maps To |
|---|---|---|
| Namespace Prefix | MyWebApp\ |
src/ directory |
| Class | MyWebApp\Http\Controllers\UserController |
src/Http/Controllers/UserController.php |
The video below explains this mapping visually.
Autoloading Classes in PHP: PSR-4 and Composer
This segment continues the previous video, explaining the PSR-1 naming convention before diving into the core PSR-4 rule of mapping namespaces to directory structures.
Watch from 04:03 to 08:36. Pay close attention to how the folder structure (app/, database/models/) is created to mirror the namespaces (App, Database\Models).
3. Configuring Composer's Autoloader
Now for the best part: you don't need to write the autoloader logic yourself. Composer provides a highly optimized autoloader out of the box. All we need to do is tell Composer how our project's namespaces map to its directories.
We do this in the composer.json file, using the autoload key.
To set up the mapping from our example above (MyWebApp\ -> src/), we would add this to composer.json:
{
"name": "your-vendor/your-project",
"require": {},
"autoload": {
"psr-4": {
"MyWebApp\\": "src/"
}
}
}
Let's break this down:
"autoload": The main key for all autoloading configuration."psr-4": Specifies that we are defining a PSR-4 mapping."MyWebApp\\": "src/": This is the rule.- The key
"MyWebApp\\"is the namespace prefix. Note the two backslashes. This is because the backslash is a special character in JSON, so it must be escaped. - The value
"src/"is the base directory that corresponds to this namespace prefix.
- The key
Generating the Autoloader
After adding or changing the autoload section in composer.json, you must tell Composer to regenerate its autoloader files. You do this with a simple command:
composer dump-autoload
This command reads your autoload configuration and updates the files in the vendor/composer/ directory, including the main vendor/autoload.php file.

This process is explained clearly in the official Composer documentation and demonstrated in the final segment of the video we've been watching.
The official Composer documentation provides the definitive guide. This section explains how to add your own code to the autoloader using the psr-4 mapping.
Read the section titled 'Autoloading'. Focus on the example showing the autoload field in composer.json and the note about having to run dump-autoload afterward.
Autoloading Classes in PHP: PSR-4 and Composer
This clip shows you how to transition from a manual autoloader to using Composer's superior implementation by configuring composer.json and running dump-autoload.
Watch from 12:33 to 17:48. This is the most important part of the lesson. It brings everything together, showing how to define the PSR-4 mapping for your own application code and use Composer to generate the necessary files.
4. Hands-on Practice
Let's put this into practice. In the project you've been working on:
-
Create a source directory: In your project's root, create a new folder named
src. -
Define a class: Inside
src, create a file namedRouter.php. Add the following code to it:<?php namespace App; class Router { public function dispatch() { echo "Router dispatched!"; } }Notice the namespace is
Appand the class isRouter. -
Configure
composer.json: Open yourcomposer.jsonfile and add theautoloadsection. Your file should look something like this:{ "require": { "cocur/slugify": "^4.0" }, "autoload": { "psr-4": { "App\\": "src/" } } } -
Generate the autoloader: In your terminal, run:
composer dump-autoload -
Use the class: Create an
index.phpfile in your project root. Add this code:<?php // This one line is all you need to load Composer's autoloader require __DIR__ . '/vendor/autoload.php'; // Use your custom class without any other require statements $router = new App\Router(); $router->dispatch(); echo "<br>"; // You can still use vendor classes too! $slugify = new Cocur\Slugify\Slugify(); echo $slugify->slugify('Hello World, this is a test!'); -
Run it: Open your terminal and run
php index.php. You should see the output from both your customRouterclass and theslugifypackage, with no manualrequirestatements for either class!
5. Optimizing the Autoloader for Production
Composer's PSR-4 autoloader is fast, but for production environments, it can be made even faster. You can ask Composer to generate a "classmap" — a simple array that directly maps every known class to its file path. This is faster because PHP doesn't have to search the filesystem to resolve class paths.
To generate an optimized classmap autoloader, you use the -o flag:
composer dump-autoload -o
This is recommended for your production deployment process. For development, the standard dump-autoload is fine, as it will automatically find new classes you create without needing to be regenerated every single time.
PHP Coding Standards, Autoloading (PSR-4) & Composer - Full PHP 8 Tutorial
This short clip from Program With Gio explains the difference between standard PSR-4 autoloading and an optimized classmap, and shows how to generate it.
Watch from 19:42 to 21:24. The key takeaway is understanding the -o flag and when to use it (in production) versus when not to (in development).
Conclusion
Congratulations! You have just configured one of the most important components of a modern PHP application. By letting Composer handle autoloading, you can focus on writing your application's logic, confident that your classes will be available right when you need them, without any manual file management.
Key Takeaways:
- Autoloading eliminates the need for manual
requireandincludestatements. - PSR-4 is the standard for mapping namespaces and class names to directories and files.
- You configure autoloading for your own code in the
"autoload"section ofcomposer.json. - The
composer dump-autoloadcommand must be run to apply any changes to your autoloading configuration. - Including
vendor/autoload.phpis the single entry point to enable all autoloading for both your code and your dependencies. - For production, use
composer dump-autoload -oto generate an optimized classmap for better performance.
Preview of the Next Lesson:
With our project structure and dependency management now on a solid, professional footing, we can move on to a new topic. Things don't always go as planned in software. In the next module, we will begin exploring Error and Exception Handling. You will learn how to configure PHP's error reporting for different environments and how to use try-catch blocks to handle runtime errors gracefully.