Middle
How to set up automatic class loading using Composer?
sobes.tech AI
Answer from AI
Class autoloading with Composer is configured in the composer.json file. Composer supports two main types of autoloading: psr-4 and psr-0, as well as file autoloading (files) and classmap definition.
The most modern and recommended method is psr-4. It links a namespace prefix to a directory.
{
"autoload": {
"psr-4": {
"MyNamespace\\": "src/",
"AnotherNamespace\\": "lib/"
},
"files": [
"config/helpers.php"
],
"classmap": [
"database/migrations",
"database/seeds"
]
}
}
psr-4: For classes starting withMyNamespace\, Composer will look for them in thesrc/directory. For classes with the prefixAnotherNamespace\– inlib/.files: Allows loading specified files on each request. Often used for non-class functions or constants.classmap: Scans specified directories or files, finds all classes, and builds a static map of their paths. Efficient for libraries without explicit namespaces or with non-standard structures.
After making changes to composer.json, you need to run the command to generate or update autoload files:
composer dump-autoload
This command creates or updates the vendor/autoload.php file, which is then included in the initial script execution point (index.php or similar):
<?php
require __DIR__ . '/vendor/autoload.php';
use MyNamespace\MyClass;
use AnotherNamespace\Utility;
$obj1 = new MyClass();
$obj2 = new Utility();
?>
Composer automatically creates the spl_autoload_register function, which will attempt to load a class when needed, using the information from the generated autoload files.