1 min read

PHP Dependency Management (Composer)

Composer is a tool for dependency management in PHP. It allows you to declare the libraries your project depends on and it will manage (install/update) them for you.


1. The composer.json File

This file describes the dependencies of your project and may contain other metadata as well.

{
    "require": {
        "monolog/monolog": "2.0.*"
    }
}

2. Basic Commands

  • composer init: Interactively creates a composer.json file.
  • composer require <package>: Adds a library to composer.json and installs it.
  • composer install: Installs dependencies defined in composer.lock. This is typically run after cloning a project.
  • composer update: Updates dependencies to the latest versions allowed by composer.json and updates the composer.lock file.

3. The vendor Directory

Composer installs all dependencies into a directory named vendor. You should generally add this directory to your .gitignore file.

4. Autoloading

Composer generates a vendor/autoload.php file. You can simply include this file and start using the classes from those libraries without extra work.

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

use Monolog\Logger;
use Monolog\Handler\StreamHandler;

// create a log channel
$log = new Logger('name');
$log->pushHandler(new StreamHandler('app.log', Logger::WARNING));

// add records to the log
$log->warning('Foo');

programming/php/php programming/php/php-namespaces