Composer for PHP: composer.json and composer require

Composer is PHP's dependency manager: it installs the libraries a project needs into vendor/, and it generates the autoloader that makes them usable, along with your own classes.

composer require nikic/fast-route   # adds the dependency and installs it
composer dump-autoload              # regenerates the autoloader after a change to the autoload section
require __DIR__ . '/../vendor/autoload.php';

$dispatcher = FastRoute\simpleDispatcher(function (FastRoute\RouteCollector $routes) {
    $routes->get('/', 'une');
});

Everything starts from composer.json: the required PHP version, the packages in require (and in require-dev for those only used during development, like PHPUnit), and the autoload rule for your classes. composer require adds a line to require, downloads the package and its own dependencies, and records the exact versions in composer.lock. You commit composer.json and composer.lock, never vendor/: composer install rebuilds it identically on another machine.

In the code, one line is enough: a require of vendor/autoload.php. From then on, every class, yours as well as a package's, is loaded the moment it is used.

5 exercises work on this concept, by writing code in the browser.

In the tracks

Related concepts

DependencyPSR-4AutoloadJSONNamespacesuseRouter