Composer – Dependency Management in PHP

September 23, 2014
0

Today's article is all about a fabulous tool for dependency management in your PHP projects. Composer solves the problem where you add a library to your application but it depends on this specific version of some other library, which also uses the yaml stuff, which needs ... you get the picture!

Composer helps us keep track of what external code our application relies on, and get it installed the right way on every copy of that application. This article will show you how to use Composer successfully in your own projects.

Get Composer

Composer is cross-platform and easy to install, so let's get it working on your system. The recommended method for *nix systems is a 2-line command:

curl -sS <a href="https://getcomposer.org/installer">https://getcomposer.org/installer</a> | php mv composer.phar /usr/local/bin/composer

There are more detailed instructions if you would rather download the file yourself and then extract and move it, and Composer is also available via homebrew for OS X. There are some good instructions for Windows on how to get and use the installer for that platform.

Check your installation is working by running the command to check the version.

composer --version

If it looks healthy (the command outputs a version number and no error messages) then you are successfully installed. Before we move on, it is worth mentioning that Composer generates warning messages when its version is more than 30 days out of date, so you'll also need to be able to update this tool. The command you want is:

composer self-update

This will download a new version of composer and replace the existing version with the new one.

Describe Your Dependencies

To use Composer, first we need to describe to it what our dependencies will be. As a really simple example, I'm going to ask it to install Monolog, an excellent PHP logging library. Information about the dependencies for a project are placed in a file called composer.json. Mine looks like this:

{ "require": { "monolog/monolog": "1.10.*" } }

This states that Monolog is a required dependency, and that it should be the newest release of version 1.10. There are some tricks to the versioning notation, so here are some examples:

1.3.* At least version 1.3.0, up to the highest minor revision number, for example 1.3.22
~1.3 At least version 1.3.0, up to the latest possible 1.* release, but not including 2.*
>1.3 Any release from 1.3.0 onwards

Install Dependencies

Now we've described our dependencies, let's get them installed! We do this with a simple command:

composer install

Here's what I see when I do that:

composer-install.png

Take a look at the output:

  1. First a package called psr/log is installed. We didn't ask for this, but Monolog requires it, so Composer installs it for us.
  2. Composer makes some suggestions about other things we might like to install (but we don't have to).
  3. Then Composer tells us it wrote the composer.lock file. This records exactly which version of each package was installed, so that every single installation of the code gets the same packages.
  4. Finally it lets us know that our autoload files are generated.

It's these last two points that we need to care about most in our applications. The composer.lock file is the really neat part of Composer; it means that every installation of this application, on each dev environment, and also on the staging/live servers, uses the exact same versions of all the dependencies. Composer uses composer.json as the template, works out what the best version of each dependency is, then records what we have in composer.lock. Next time, since the composer.lock file is present, it uses that as the template.

Take a look at what I have in my directory now that I have run that command:

filesystem.png

These files are typically either at the top level of our project, or one level down in an src/ folder or equivalent. The vendor folder holds all our library code, and the composer.* files describe the dependencies.

Use Composer With Source Control

Composer is designed to play nicely with source control. It allows us to avoid seeing changesets that relate to our libraries rather than our actual application, and draws an excellent boundary between our code and its dependencies.

The recommended setup is this:

  • composer.json and composer.lock are both included in your source control project
  • The vendor/ directory is completely ignored, add “vendor/” to your .gitignore file if you're on git, or equivalent for other systems.

Each time someone makes a change to composer.json or composer.lock, everyone else needs to run composer install again to get the correct dependencies.

Composer Makes Autoloading Simple

Remember when we ran the composer install command and it told us it generated our autoload files? This is one of the magical things about Composer – each package has its own autoload rules, and Composer loads them when it gets the code.

If you haven't come across autoloading in PHP before, it's a feature that allows you to give general instructions about where to find code for classes, rather than having to explicitly include every file in your code. PHP takes the classname and uses the rules in the autoloader to find that code and parse it when it's needed, rather than having everything included just in case. You can read more about autoloading in the manual.

To use any of your installed libraries in your application, simply add this line to the top of your file:

require “/path/to/vendor/autoload.php”;

This brings in an autoloader that allows PHP to find any of the code that it needs to load the classes in the libraries that Composer installed – very handy indeed.

Updating Libraries

Sometimes, we might want to add a new dependency to our composer.json file, or get newer versions of the libraries we already had defined there. For this, whether we changed composer.json or not, we need to run a new command:

composer update

This command will update the composer.lock to the newest versions of all packages defined in the file. To be a bit more specific you can also specify which package you want to update – so if you've just added a new dependency but don't want to update everything else, you can use that.

This command can be confusing, since it's tempting to think you need to “update” to get newer versions of code when you see that composer.lock has changed. The composer install command will bring in whichever versions are named in composer.lock, but composer update will change the contents of that file, so use it with caution!

Composer Helps Manage Code

The biggest thing that Composer offers is the ability to just not worry about any code other than what's specific to what you're working on. It's standard throughout PHP projects today, and as a tool it's hugely increased in both ability and adoption.

Some related resources if you'd like to learn more:

Using Composer in Drupal

Check out this excellent article by Chris Pliakas Using Composer Manager to get off the Island Now for more information on using Composer in Drupal.

Guest author dossier

  • Name: Lorna Jane Mitchell
  • Twitter: @lornajane
  • Website: http://lornajane.net
  • Work affiliation: Freelance, "I work where there are people who need me."
  • Drupal/FOSS role: Project lead on joind.in, PHP writer and speaker, "I don’t know any Drupal but I keep finding excuses to hang out with the community."
  • Current projects: Joind.in mainly, but I just had some contributions accepted to XHGui.
  • When/which PHP you started with: PHP 4.2 in 2002
  • About: Lorna is a web development consultant and author based in Leeds, UK. Her books include "PHP Master", "PHP Web Services" and "N Ways To Be A Better Developer", and she loves to write for other outlets such as netmagazine and her own blog http://www.lornajane.net. When she's not writing either code or words for a living, Lorna leads the Joind.In open source project; a tool to enable communities to give real-time, public feedback to speakers and organisers of events. Lorna has spoken at events around the world giving both keynotes and technical talks and is available for hire on interesting projects.

Also in the Future of PHP series

  1. Future of PHP series landing page
  2. Perspectives on the future of PHP – "The Future of PHP" series intro, Jeffrey A. "jam" McGuire
  3. The future of PHP ... at a distance – Lukas Kahwe Smith
  4. Composer – Dependency Management in PHP – Lorna Mitchell
  5. The Future of PHP is Shared Power Tools – Ryan Weaver
  6. PHP is getting Faster – Richard Miller
  7. PSR-What? Shared Standards for a Bright Future – Lorna Mitchell
  8. Voices of the ElePHPant / Acquia Podcast Ultimate Showdown Part 1 & Part 2 - Acquia Podcast audio/video with Cal Evans and Jeffrey A. "jam" McGuire
  9. PHP: Under the Hood, Running the Web - Michelangelo van Dam
  10. A Symfony Shop Embraces Drupal 8 & Gets Down to Business - Acquia Podcast audio/video interview with Chris Jolly
  11. Building Bridges, Linking Islands - Larry Garfield
  12. Drupal & PHP: Linking Islands, the podcast – Part 1 & Part 2 - Acquia Podcast audio/video interview with Larry Garfield
  13. PHP: Getting the job done, really easily – Acquia Podcast audio/video interview with Stephan Hochdörfer
  14. Get more done, better & faster – together. – Acquia Podcast audio/video interview with Dustin Whittle
  15. New Wave PHP – Audio/video interview and conference session presentation with Lorna Jane Mitchell
  16. Writing secure PHP: "F.I.E.O." and more – Acquia Podcast audio/video interview with Chris Cornutt
  17. PHP: The entire world is your development team – Beth Tucker Long – Acquia Podcast audio/video interview

Image credit

Lorna_Jane_1.jpg image by Rob Allen https://www.flickr.com/photos/akrabat/4639915028

License: https://creativecommons.org/licenses/by-nd/2.0/

Lorna Jane Mitchell

Sign-up for our Developer Blog Newsletter

Thanks!

Add comment

By submitting this form, you accept the Mollom privacy policy.