Composer

Composer is a tool for dependency management in PHP. It allows you to declare the dependent libraries your project needs and it will install them in your project for you.

Composer is not a package manager. Yes, it deals with "packages" or libraries, but it manages them on a per-project basis, installing them in a directory (e.g. vendor) inside your project. By default it will never install anything globally. Thus, it is a dependency manager.

The problem that Composer solves is this:

a) You have a project that depends on a number of libraries.

b) Some of those libraries depend on other libraries.

c) You declare the things you depend on.

d) Composer finds out which versions of which packages need to be installed, and installs them (meaning it downloads them into your project).

Installation

Composer requires PHP 5.3.2+ to run. There are 2 ways to install composer:

Locally

Installing Composer locally is a matter of just running the installer in your project directory:

curl -sS https://getcomposer.org/installer | php

Globally

curl -sS https://getcomposer.org/installer | php
mv composer.phar /usr/local/bin/composer

Note: If the above fails due to permissions, run the mv line again with sudo.

Then, just run composer in order to run Composer instead of php composer.phar.

Note_: The .phar extension provides a way to put entire PHP applications into a single file called a "phar" (PHP Archive) for easy distribution and installation.

Usage

mkdir composer-example
cd composer-example

For Composer, you declare your dependencies in a composer.json file. Create one with the following JSON:

{
  "require": {
    "twig/twig": "1.18.0"
  }
}

Only thing left to do is to actually install our dependencies:

composer install

And you’ll get the following output:

Loading composer repositories with package information
Installing dependencies (including require-dev)
  - Installing twig/twig (1.18.0)
    Loading from cache

Writing lock file
Generating autoload files
Let’s list out some folders to see what actually happened:

Let's see what had happened:

ls
composer.json composer.lock vendor
ls vendor
autoload.php composer twig

We can see that Composer created a vendor/ directory that contains the twig package.

After installing the dependencies, Composer writes the list of the exact versions it installed into a composer.lock file. This locks the project to those specific versions.

Conclusion

When you’re using Composer, you check the following files into your repository:

composer.json
composer.lock

That’s it. Add vendor/ to your .gitignore and let Composer handle it. Now whenever wants to setup your project, they just run the standard git clone followed by composer install.

Sources: