PHP Autoloading Primer Autoloading with Composer

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

Composer 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 its a PSR-4 mapping of a namespace to a directory: the /src directory resides in your projects root folder, on the same level as the /vendor directory is. An example filename would be src/Foo.php containing an 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.


When you including the /vendor/autoload.php file it will return an instance of the Composer Autoloader. You might store the return value of the include call in a variable and add more namespaces. This can be useful for autoloading classes in a test suite, for example.

$loader = require __DIR__ . '/vendor/autoload.php';
$loader->add('Application\\Test\\', __DIR__);


Got any PHP Question?