Getting Started with Composer: Simple Examples

Getting Started with Composer: Simple Examples

Last updated:

DISCLAIMER: This tutorial is intended for Linux (preferably Ubuntu) users.

Composer is a dependency manager for PHP.

composer is to PHP as gem is to Ruby.

Installing

This will download a PHP executable file ( composer.phar ) into your machine.

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

Create a composer.json file in your project root

Create a file called composer.json where your project is and add this to the file:

(This is just a test, you can modify this later):

{
    "require": {
        "php": ">=5.1.0"
    }
}

cd to your project root and run composer

(It probably got installed to ~/composer.phar or perhaps the directory you were in when you downloaded it via cURL)

/var/www/my_project$ ~/composer.phar install

This will verify that you current machine can satisfy the dependencies you've specified in composer.json (in this case, just that you have php installed).

You can add other projects and libraries (like a web framework) to composer.json and run composer.phar install on it - this will cause composer to install any dependencies you do not have installed.


Extras

Add composer to your PATH

composer.phar is an executable file. You can make it globally accessible the same way you do other scripts: add the directory it's located in to your $PATH environment variable.

Where the libraries get installed

A directory called vendor/ will probably be created for you the first time you run composer install. This directory will be located on the same directory level as your composer.json file.

composer.lock

This is when a composer install gets instantiated. This is useful for knowing the exact setup that gets your application working. When available, composer install uses this file as reference instead of composer.json.

References