🎼 Composer

Updated at 2015-05-05 05:35

Composer is a command line package manager for PHP libraries. This note contains basic Composer usage tips.

composer -V
# Composer version 0c85ca426d6e8235366340f29ad0e6aab1747b83 2014-05-19 10:17:07

Basic commands:

  • composer init: Creates a new composer.json file for a new project in the current directory.
  • composer install: Downloads and installs dependencies from composer.json and composer.lock into vendor Creates composer.lock if it doesn't exist; it contains specific package versions you are using.
  • composer update: Updates all packages defined in composer.lock.
  • composer require vendor-name/package-name: Installs a package and writes the dependency to composer.json

You specify your project's PHP dependencies in composer.json file.

    "name": "vendor-name/project-or-library-name",
    "authors": [
            "name": "Ruksi",
            "email": ""
    "require": {
        "php": ">=5.3.2",
        "nesbot/carbon": "1.13.0"

If you require a feature, there probably is a package for that. Full list of Composer packages is available at Packagist. The packages I use frequently are listed at PHP libraries note.

Know what to commit. Always commit composer.json and composer.lock files.

  • composer.json contains original definitions of your dependencies.
  • composer.lock contains exact version of your dependencies and is created on the first composer install and rewritten on each composer update.
  • You usually don't want to commit the vendor/ directory.

Never do composer update in production. It will overwrite your lock-file and possibly cause some dependencies to update, potentially leading to problems.

  • In development: composer install, composer update
  • In production: composer install

Include the autoloader. You must include composer autoloader to use the installed packages.

require 'vendor/autoload.php';
$log = new Monolog\Logger('name');

Extend the autoloader. You can add your own directories to autoloader by editing composer.json. You have to run another composer install after each change.

    "autoload": {
        "psr-4": {"YourNamespace\\": "your-src/"}

You can manipulate autoloader at runtime. Useful for e.g. unit testing.

$loader = require 'vendor/autoload.php';
$loader->add('YourNamespace\\Test\\', __DIR__);