Autoloading with Composer
suggest changeComposer generates a vendor/autoload.php file.
You might simply include this file and you will get autoloading for free.
require __DIR__ . '/vendor/autoload.php';
This makes working with third-party dependencies very easy.
You can also add your own code to the Autoloader by adding an autoload section to your composer.json.
{
"autoload": {
"psr-4": {"YourApplicationNamespace\\": "src/"}
}
}
In this section you define the autoload mappings. In this example it's a PSR-4 mapping of a namespace to a directory: the src/ directory resides in your project's root folder, on the same level as the vendor/ directory. An example filename would be src/Foo.php containing a YourApplicationNamespace\Foo class.
Important: After adding new entries to the autoload section, you have to re-run the command dump-autoload to re-generate and update the vendor/autoload.php file with the new information.
In addition to PSR-4 autoloading, Composer also supports PSR-0, classmap and files autoloading. See the autoload reference for more information.
Including vendor/autoload.php returns the Composer autoloader. You can store that return value and register more namespaces. This can be useful for autoloading classes in a test suite, for example. Use addPsr4() for a PSR-4 prefix; add() registers a PSR-0 prefix instead.
$loader = require __DIR__ . '/vendor/autoload.php';
$loader->addPsr4('Application\\Test\\', __DIR__);