Getting Started with Composer

I've got an application (okay, scratty PHP script) which glues together some API things and shows them onto a dashboard for me. Recently, I updated it to use Guzzle as the consuming client, since twitter now needs me to authenticate (I wrote about that if you're interested), and I used Composer to bring the new library in. It was very simple so I thought I'd share it as it's quite minimal example, and those are my favourite kind.

First of all, you'll need to either install composer, or at least get the .phar - these examples use the composer.phar file from under the "Manual Download" section.

Composer comes with instructions, for a list of commands type:

php composer.phar list

Once you've got composer ready to go, then we can move on and configure it.

State Your Dependencies

All you need to do to use composer is create its configuration file and then tell it to do its magic :) All I want here is the Guzzle library, so my config file is rather simple:

{ "require" : { "guzzle/guzzle" : "3.7" } }

Get the Libraries

From this point, Composer can do the rest itself. It will fetch all the libraries you set in the config file, but will also get any dependencies of those libraries. To ask it to do this, just type:

php composer.phar install

This will download all the libraries you need and place them in a vendor directory. In the case of Guzzle, it depends on other libraries (from the Symfony project), so my vendor directory now contains:

. ├── autoload.php ├── composer ├── guzzle └── symfony

And there you have it - all the libraries you need are in place.

Tell Your Application About Its Dependencies

One more step - just add the following line into your application to make those new libraries available to it:

require 'vendor/autoload.php';

There you go :) Enjoy using Composer even in existing/legacy applications, projects that aren't built in "the one true way" or really anywhere else you don't want to have to include libraries in your repositories.

Oh, and one more tip if you're just getting started: add the vendor folder to your source control "ignore" file.

Further Reading

Nice post from Cal about including non-composer libs in your autoloader: http://blog.calevans.com/2013/07/21/using-3rd-party-libraries-in-composer-projects/

Composer documentation: http:// http://getcomposer.org/doc/