Autoloading with Composer

suggest change

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__);

Feedback about page:

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


Autoloading primer:
* Autoloading with Composer

Table Of Contents
2 Arrays
4 Types
5 Autoloading primer
10 Cookies
14 JSON
15 SOAP
17 cURL
19 XML
21 Traits
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