1. What is Composer?
Composer is the official dependency manager for PHP. It manages external libraries, packages, and frameworks required by your project, ensuring matching version constraints and automated dependency resolution.
2. The composer.json File
Every Composer-driven project features a composer.json file at its root specifying metadata and required packages:
{
"name": "cbt/portal-backend",
"description": "Online CBT Examination Platform API",
"require": {
"php": "^8.1",
"guzzlehttp/guzzle": "^7.8",
"vlucas/phpdotenv": "^5.6"
},
"autoload": {
"psr-4": {
"App\\": "src/"
}
}
}
3. PSR-4 Autoloading Standard
Before PSR-4, PHP developers had to manually write dozens of require_once lines at the start of every script. The PSR-4 standard maps PHP namespaces directly to directory paths.
For example, if App\ maps to src/, then:
App\Controllers\AuthControllerresolves automatically tosrc/Controllers/AuthController.php.App\Models\Userresolves automatically tosrc/Models/User.php.
4. Using Autoloading in Your Code
After running composer install or composer dump-autoload, include the single autoloader file at your application entry point:
load();
// Instantiate custom controller without manual require
$auth = new AuthController();
$auth->handleLogin();