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 acomposer.jsonfile.composer require <package>: Adds a library tocomposer.jsonand installs it.composer install: Installs dependencies defined incomposer.lock. This is typically run after cloning a project.composer update: Updates dependencies to the latest versions allowed bycomposer.jsonand updates thecomposer.lockfile.
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');