PHP Autoloading with Composer


Example

While composer provides a system to manage dependencies for PHP projects (e.g. from Packagist), it can also notably serve as an autoloader, specifying where to look for specific namespaces or include generic function files.

It starts with the composer.json file:

{
    // ...
    "autoload": {
        "psr-4": {
            "MyVendorName\\MyProject": "src/"
        },
        "files": [
            "src/functions.php"
        ]
    },
    "autoload-dev": {
        "psr-4": {
            "MyVendorName\\MyProject\\Tests": "tests/"
        }
    }
}

This configuration code ensures that all classes in the namespace MyVendorName\MyProject are mapped to the src directory and all classes in MyVendorName\MyProject\Tests to the tests directory (relative to your root directory). It will also automatically include the file functions.php.

After putting this in your composer.json file, run composer update in a terminal to have composer update the dependencies, the lock file and generate the autoload.php file. When deploying to a production environment you would use composer install --no-dev. The autoload.php file can be found in the vendor directory which should be generated in the directory where composer.json resides.

You should require this file early at a setup point in the lifecycle of your application using a line similar to that below.

require_once __DIR__ . '/vendor/autoload.php';

Once included, the autoload.php file takes care of loading all the dependencies that you provided in your composer.json file.

Some examples of the class path to directory mapping:

  • MyVendorName\MyProject\Shapes\Squaresrc/Shapes/Square.php.
  • MyVendorName\MyProject\Tests\Shapes\Squaretests/Shapes/Square.php.