Re-Introducing Composer – the Cornerstone of Modern PHP Apps

In this article, we will tackle the basics of Composer, and what makes it such a powerful and useful tool.

Before we go into detail, there are two things that we need to have in mind:

Essentially, Composer allows you to declare and manage every dependency of your PHP projects.

Let’s now install Composer so we can see it in action.

Composer logo

Installation

There are two ways of installing Composer: locally and globally. Because Composer is such a useful and widespread tool, I always recommend installing it globally, as you’ll probably be working on more than one project at once.

Note that if you use an environment like Homestead Improved, it’s installed globally by default. If you’re unfamiliar with Vagrant and Homestead, this post will clear things up, and if you’d like to dive deeper, this book will reveal some wild mysteries to you.

To install Composer, follow the instructions for your operating system.

If you’re on a Unix system, after installing it you can run the command:

mv composer.phar /usr/local/bin/composer

This moves the composer.phar file to a directory that’s on your path (the location of your filesystem where the OS looks for executable files by default). This way, you can use just the composer command instead of composer.phar.

Running the composer command shows the information page:

Composer main information

Some of Composer’s more useful commands are:

We will focus our attention on composer init, composer create-project and composer require.

Using Composer

To manage dependencies in a project, Composer uses a json file. This file describes all the dependencies, and holds some metadata as well.

In this example we will create a new PHP project in which we will need PHPUnit for our unit testing. There are several ways to use Composer to manage this dependency.