Composer Autoloader
Part of the Object Oriented Programming section of Coddy's PHP journey — lesson 13 of 91.
Writing your own autoloader works, but real PHP projects use Composer to handle autoloading automatically. Composer reads your project's configuration and generates an optimized autoloader that follows PSR-4 standards.
The configuration lives in a composer.json file at your project root. Here's how you define the autoloading rules:
{
"autoload": {
"psr-4": {
"App\\": "src/"
}
}
}This tells Composer that any class starting with App\ should be loaded from the src/ directory. After setting this up, Composer generates the autoloader files in a vendor/ directory.
To use Composer's autoloader, you only need one line at the top of your entry file:
<?php
require 'vendor/autoload.php';
use App\Models\User;
use App\Services\Logger;
$user = new User("Alice");
$logger = new Logger();
That single require statement handles all class loading for your entire project. You can define multiple namespace mappings if needed:
{
"autoload": {
"psr-4": {
"App\\": "src/",
"Tests\\": "tests/"
}
}
}Key Point: Composer's autoloader eliminates manual file includes and ensures consistent class loading across your project. It's the standard approach used by virtually all modern PHP applications and frameworks.
Challenge
EasyLet's build a small application that uses Composer's autoloading approach to organize classes across multiple files. You'll simulate how a real PHP project structures its code with PSR-4 namespaces and a central autoloader.
You'll create four files that work together:
src/Models/Product.php— Define aProductclass in theApp\Modelsnamespace. It should havepublic $nameandpublic $priceproperties, a constructor that accepts and sets both values, and agetInfo()method that returns"[name]: $[price]".src/Models/Customer.php— Define aCustomerclass in theApp\Modelsnamespace. It should have apublic $nameproperty, a constructor that accepts and sets the name, and agreet()method that returns"Welcome, [name]!".vendor/autoload.php— Create a simple autoloader usingspl_autoload_registerthat mimics Composer's behavior. It should map theApp\namespace prefix to thesrc/directory, converting namespace separators to directory separators and appending.phpto load the correct file.index.php— This is your entry point file. Require the autoloader fromvendor/autoload.phpwith a single line, then use theusekeyword to import bothApp\Models\ProductandApp\Models\Customer. Create aProductwith name"Laptop"and price999, and aCustomerwith name"Alice". Print the result of callinggreet()on the customer andgetInfo()on the product (each on its own line).
The key concept here is that your index.php only needs one require statement to load the autoloader — after that, all classes are loaded automatically when you use them. This is exactly how modern PHP frameworks and applications work with Composer.
Cheat sheet
Composer automates class loading by reading a composer.json configuration file and generating an optimized autoloader that follows PSR-4 standards.
Define autoloading rules in composer.json:
{
"autoload": {
"psr-4": {
"App\\": "src/"
}
}
}This maps the App\ namespace to the src/ directory. Composer generates autoloader files in a vendor/ directory.
Use Composer's autoloader with a single require statement:
<?php
require 'vendor/autoload.php';
use App\Models\User;
use App\Services\Logger;
$user = new User("Alice");
$logger = new Logger();
Define multiple namespace mappings if needed:
{
"autoload": {
"psr-4": {
"App\\": "src/",
"Tests\\": "tests/"
}
}
}Composer's autoloader eliminates manual file includes and is the standard approach in modern PHP applications.
Try it yourself
<?php
// TODO: Require the autoloader from vendor/autoload.php
// TODO: Use the 'use' keyword to import App\Models\Product
// TODO: Use the 'use' keyword to import App\Models\Customer
// TODO: Create a Product with name "Laptop" and price 999
// TODO: Create a Customer with name "Alice"
// TODO: Print the customer's greet() result
// TODO: Print the product's getInfo() result
?>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe $this KeywordMethodsPropertiesConstructor (__construct)Destructor (__destruct)Recap - Simple Calculator4Inheritance
Basic InheritanceThe parent:: KeywordMethod OverridingThe final KeywordAbstract ClassesRecap - Employee Hierarchy7Encapsulation
Public, Protected, PrivateAccess Modifiers in DepthGetters and SettersInformation HidingConstructor Promotion (8.0)Recap - Student Records System2Namespaces & Autoloading
Introduction to NamespacesThe use KeywordPSR-4 Autoloading StandardComposer AutoloaderRecap - Organized Project5Interfaces & Contracts
Introduction to InterfacesImplementing InterfacesMultiple Interface ImplementInterface vs Abstract ClassType Hinting with InterfacesRecap - Shape Calculator8Magic Methods
Magic Methods Introduction__toString & __debugInfo__get, __set, __isset, __unset__call & __callStatic__clone & Object Cloning__serialize & __unserializeRecap - Custom Collection11Type System & Error Handling
Type DeclarationsNullable TypesUnion & Intersection TypesException ClassesCustom Exception HierarchyTry, Catch, FinallyRecap - Form Validator14Project: Library Management
Project OverviewBook and User Classes3Class Properties
Instance vs Static PropertiesConstants in ClassesStatic Methods & PropertiesPrivate & Protected PropertiesReadonly Properties (PHP 8.1)Recap - Bank Account Manager6Polymorphism
Method Overriding RevisitedPolymorphism via InterfacesType Hinting & Union TypesLate Static BindingRecap - Payment Processor9Traits
Introduction to TraitsUsing Multiple TraitsTrait Conflict ResolutionAbstract Methods in TraitsTraits vs Inheritance12Design Patterns Part 1
Intro to Design PatternsSingleton PatternFactory PatternObserver PatternStrategy Pattern