Composer Dependency Tutorial

composer

You’ve likely heard of Composer, the dependency management system for PHP. If you’ve been following along with our Laravel Tutorials, you’ll note that we have been making use of Composer to get our projects up and running. Whether you have Composer running on a *nix system like Ubuntu, or Composer running on a Mac or Windows, the process is essentially the same. Let’s dig into Composer a bit more so that we have a solid grasp of what it is, how it works, and how to best use it.

The Director of the Symphony

When you visit the home page for Composer, they have a nice picture of an actual Composer who would be directing a Symphony. Think of all those nice folks playing their various instruments as various pieces of software with the Composer being the director that helps them all work together. Just as a real Composer helps musicians and instruments work together to create something bigger than any one of them could do alone, the software Composer acts as a director of sorts that manages dependencies and relationships between various PHP software packages. Cool stuff indeed!

Framework Agnostic

We’ve been using composer with our Laravel projects and tutorials, but Composer is much bigger than that. By using Composer you can plug in software packages into your favorite PHP framework, whether that be Laravel, Codeigniter, Yii, Symfony, Zend, Slim, FuelPHP, and more. The benefit here is that you do not become so much dependent on learning all of the different nuances of a framework, only to have to start over if you need to work on a different project that uses a different framework.

Install Composer

First up, we need to install Composer. We can do this easily on *nix or Windows systems.

*nix based

$ cd /var/www/mykillerapp
$ curl -s http://getcomposer.org/installer | php

To see all the commands available to run you can do the following

$ php composer.phar

Windows Based

For the lazy among us the like a one click installation, click https://getcomposer.org/Composer-Setup.exe and run the program. The installer downloads composer and configures the system so you can run composer from any directory. In fact, in windows explorer, if you right click on various folders you’ll see options like Composer Init, Composer Options, Self Update, Show Help, Run as Admin, and Use Composer Here. Quite handy indeed!

Available Commands

Once Composer is installed you can run a slew of commands from the command line. Hit the official docs for the exhaustive details, or check out this list here of the most commonly used ones you might run into: install, update, require vendor-name/package-name, init, create-project symfony/framework-standard-edition dir/, run-script, search my keywords, validate, config --list, self-update, status, diagnose, help, show, global, licenses, archive, depends vendor-name/package-name, dump-autoload --optimize

Check out this awesome Composer Cheat Sheet for Developers for an explanation of each command.

composer.json

The configuration file for Composer is your composer.json file. It contains everything to tell Composer how to operate and consists of, you guessed it, json data! The data within specifies settings and package requirements for a given application. A really basic composer.json file would look like this:

This will require the “pieceofresistance” package, created by “lego”, and will require any version. More commonly, you might like to use a specific verison like this:

"lego/pieceofresistance": "2.0.3"

Often times you will see major versions specified and minor versions given the wildcard like this:

"lego/pieceofresistance": "2.0.*"

Cool! You now have a package (fictional in this case) so you can run the install command. This is when the magic starts happening. If you remember manually trying to find and download different scripts to try out on your local server, rejoice! With this approach, the files start downloading in the background and get placed into the vendors/ folder at the root of the application. Better yet is to specify where you would like the files placed in the composer.json like so:

Let’s now actually use Composer to specify some packages to download. The first example will be an really fantastic PHP Console that you can use for testing snippets of PHP without having to actually create a PHP file, save it, load it, and so on. We’ll make use of the seld/php-console package.

Using composer init

Composer init helps guide you through the process of creating a valid json file for Composer to use.


C:wampwwwphpcon>composer init

Welcome to the Composer config generator

This command will guide you through creating your composer.json config.

Package name (/) [vegibit/phpcon]: demo/forfun
Description []: just a test of composer
Author: fred
Minimum Stability []: dev
License []:

Define your dependencies.

Would you like to define your dependencies (require) interactively [yes]? no
Would you like to define your dev dependencies (require-dev) interactively [yes]? no

{
“name”: “demo/forfun”,
“description”: “just a test of composer”,
“authors”: [
{
“name”: “fred”,
“email”: “fred@flinstone.com”
}
],
“minimum-stability”: “dev”,
“require”: {

}
}

Do you confirm generation [yes]? y

C:wampwwwphpcon>

If we now look at the composer.json file created for us, it will appear as so:

We didn’t specify any dependencies during the composer init command, so you’ll see that the require object is empty. We can manually update it once we find something from https://packagist.org/ that we would like to use. In this example we are going to use https://packagist.org/packages/seld/php-console. We can now update composer.json manually like so:

Now pretend you didn’t do this manually, or simple delete any entries in the require object. We can also complete the same task using composer require

C:wampwwwphpcon>composer require
Search for a package []: seld

Found 3 packages matching seld

[0] seld/jsonlint
[1] seld/php-console
[2] seld/slippy

Enter package # to add, or the complete package name if it is not listed []: 1
Enter the version constraint to require []: 1.4.0
Search for a package []:
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
– Installing seld/php-console (1.4.0)
Loading from cache

Writing lock file
Generating autoload files

C:wampwwwphpcon>

Excellent! This updates your composer.json file and pulls in the dependencies in one shot.

Note that there is also a new file in the directory called composer.lock. This is a *very* important file! Basically what it does is lock in the versions you have specified in the composer.json file so that if you or someone else runs composer install in the future, only those specified versions will be installed, *not* the latest and greatest versions which might cause bugs or breakage of your app.

You can bypass this by using composer update. What this command does is pretend that a composer.lock file is not there, or just ignores it. Composer will look for any wildcard * characters in the composer.json file and download the latest versions for the dependencies. Maybe you want this, maybe you don’t. Just be aware of the difference between composer install and composer update.

If you look in the project directory you’ll now notice a vendor directory in addition to the composer.json and composer.lock files. If we open up the vendor directory, you’ll see the composer folder and the seld folder dependency in addition to an autoload.php file. Inside of the seld folder we have the package we were looking for, php-console. Now check this out, let’s browse to http://localhost/phpcon/vendor/seld/php-console/ and observe the result in all of it’s glory:

php console download composer

There you go. Your own PHP console sandbox to quickly test snippets of code with the click of a button. No downloading all kinds of zip files, extracting them, copy and paste, none of it. Just use composer, enter a few commands, and get yourself a nice piece of software to test and use.

Lets add another requirement to this project.

C:wampwwwphpcon>composer require
Search for a package []: twitter/bootstrap

Found 15 packages matching twitter/bootstrap

[0] twitter/bootstrap
[1] libra/twitter-bootstrap-assets
[2] mwillbanks/zfc-twitter-bootstrap
[3] kvdh/symfony-twitter-bootstrap
[4] toa/twitter-bootstrap-bundle
[5] phpugl/twitter-bootstrap-bundle
[6] evheniy/twitter-bootstrap-bundle
[7] typo3/twitter-bootstrap
[8] jlong/sass-twitter-bootstrap
[9] kvdh/symfony-twitter-bootstrap-datetime-picker
[10] twitter/bootstrap-bundle
[11] ppi/twitter-bootstrap-module
[12] patricktalmadge/bootstrapper
[13] komola/bootstrap-zend-framework
[14] yiisoft/yii2-bootstrap

Enter package # to add, or the complete package name if it is not listed []: 0
Enter the version constraint to require []: dev-master
Search for a package []:
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)

– Installing twitter/bootstrap (dev-master 541a75f)
Downloading: 100%

Writing lock file
Generating autoload files

C:wampwwwphpcon>

Again, this updates our composer.json and pulls in the dependency all at once, cool!

Using Composer is a great way to simplify workflow and manage dependencies in your PHP projects, whether you’re working on UNIX, Linux, Mac, or Windows. Not only that, Composer offers powerful autoloading features that we’ll tackle in our next episode. Try it out today and see what you think.

Thank you for reading Composer Dependency TutorialPlease do share using the buttons below!