Autoloading PHP Classes the Composer Way
Learn about autoloading our own classes as well as other non-Packagist classes with the Composer autoloader.
Autoloading allows us to use PHP classes without the need to require
or include
them and is considered a hallmark of modern programming.
Autoloading Packagist code libraries
Previously, we saw that all it takes to autoload Packagist libraries is to add the following line (at the top of our scripts) that requires the Composer built-in autoloader:
require_once __DIR__ . '/vendor/autoload.php';
However, when we’re working with our own classes (or with non-Packagist classes), we may need to be somewhat more savvy.
Composer autoloading can work in two main ways—through direct autoloading of classes or through PHP Standard Recommendation (PSR) standards.
Autoloading classes with the composer
The simplest way is to autoload each class separately. For this purpose, all we need to do is define the array of paths to the classes that we want to autoload in the ...