Autoloading with Composer

suggest change

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:

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Composer dependency manager:
* Autoloading with Composer

Table Of Contents
2 Arrays
4 Types
10 Cookies
14 JSON
15 SOAP
17 cURL
19 XML
21 Traits
24 Composer dependency manager
35 UTF-8
36 URLs
38 PHPDoc
41 Loops
44 Closur
72 YAML
77 Cache
78 Streams
81 PDO
82 SQLite3
83 Sockets
87 MongoDB
93 IMAP
94 Redis
95 Imagick
102 APCu
108 PSR