Auto-load files using the namespace through the loader composer

March 15, 2017 14 Yehor Rykhnov

A brief instruction about uploading files using composer.

If you write your library on php and use composer, you can organize startup of your files with the help of the composer loader. This is convenient if you want to include files of both third-party and your libraries.

The composer autoloader can be configured to work on both the psr-0 standard and the more advanced psr-4 . Let us dwell on the last standard. And so, if you already used composer, you must have, in addition to other files and folders you may have, composer.json, vendor/autoload.php and your directory, for example, mylib/mypacket. Add a few lines to the composer.json file:

...
"autoload": {
    "psr-4": {
        "mylib\\mypackage\\" : "mylib/mypackage"
    }
}
...

Installing the composer:

composer install

And connect the composer autoloader to your file where you want to upload your files:

require_once "vendor/autoload.php";    

// Example of calling a class from your library use mylib\mypackage\MyTestClass; $myTestClass1 = new MyTestClass();

Example class:

// my-lib/my-package/MyTestClass.php
namespace mylib\mypackage;
class MyTestClass { // Some code }

Done.