Composer: the PHP dependencies manager

PHP Composer

(originally posted on my Portuguese blog at rberaldo.com.br)

Composer is the most widely used dependency manager for PHP in the world today. It allows you to define external libraries used in your project in a simple way. Composer takes care of downloading the library and automatically loading it into your application.

It’s ridiculously easy to use Composer! It does all the heavy lifting of managing libraries, downloading the correct versions, and integrating them into your project.

In other words, if you’re not using it yet, you’re definitely wasting a LOT of time and productivity!

Keep reading this article as I’ll explain how to install and use this wonderful tool.

Composer Installation

The installation process differs for Windows and Linux/Mac systems. I’ll cover them separately.

Installation on Linux and Mac

On Linux and Mac, we can leverage the wonderful command-line tools, which greatly simplify our programming tasks.

Open the terminal and run this command:

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

The command above downloads the Composer installer using curl and runs it with the PHP interpreter.

If you don’t have curl installed, the command will fail. You can install curl or use the command below, which achieves the same result:

php -r "readfile('https://getcomposer.org/installer');" | php

After running the command, if you use ls, you’ll see that the composer.phar file is now in your directory.

You can use the following command to test the installation:

php composer.phar

Since you’ll use Composer frequently across various projects, I recommend installing it globally instead of downloading it for each application. This way, you can execute it from any directory without the need for re-downloading.

To do this, copy the composer.phar file to a directory that’s part of your system’s PATH. To simplify things, rename it to composer without an extension.

Copy the file to the /usr/local/bin/ directory with the mv command:

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

Note that /usr/local/bin/ is a protected directory, and you’ll need root permission to write to it. That’s why we used sudo to run the command.

Now Composer is installed globally. You can simply type composer in the terminal from any directory and use it as needed.

Installation on Windows

The easiest way to install Composer on Windows is by using the installer. Manual installation is also an option if you prefer.

Download the installer here. After downloading, run the installer and follow the steps. The installer will add Composer to your Windows PATH, allowing you to execute it from any directory.

Note that if you have a command prompt window open, you should close and reopen it. This is necessary to load the changes to the PATH.

If you prefer manual installation, click here and follow the commands described in the official documentation.

Installing Dependencies

To install a dependency, use the command composer require <vendor_name/project_name>. A package is identified by two parts: vendor_name is the name of the package owner, and project_name is the actual project name.

For example, if you want to install Slim, you would require the package slim/slim as follows:

composer require slim/slim

After a few seconds, Slim will have been automatically downloaded. The composer.json and composer.lock files will be created automatically. The Slim library (as well as all other dependencies) will be stored in the vendor directory.

The composer.json file is the main configuration file. It stores dependencies, project names, and more.

The composer.lock file is managed by Composer to track versions, source locations, and other details. You don’t need to (and shouldn’t) modify it.

The vendor directory contains the autoloader and all your project’s dependencies.

You can manually change the composer.json file if you prefer, but it’s quicker and more convenient to use the composer require command, which updates the file and automatically downloads the library.

Using Dependencies

Once you’ve declared and downloaded a dependency, you can use it throughout your project as long as Composer’s autoloader is loaded.

If you have a Bootstrapping file, that’s the perfect place to include Composer’s autoloader. You can read more about Bootstrapping and Initialization files in my article.

Let’s do a quick test using Slim, which we downloaded earlier.

In the current directory (where composer.json is located), create an index.php file. In this file, you only need to include the vendor/autoload.php file, and you’ll have access to all the dependencies managed by Composer.

Create index.php with this content:

<?php

require 'vendor/autoload.php'; 

$app = new \Slim\Slim(); 
$app->get('/', function() {
    echo "It works!";
});
$app->run();

You can start the built-in PHP server and test it in your browser. Start the server on port 8000 with this command:

php -S localhost:8000

Then, simply access the URL http://localhost:8000 in your browser, and you’ll see the message “It works!”

There you go, as you can see, it’s that simple! 🙂

Updating Dependencies

Being a dependency manager, Composer is responsible for updating downloaded packages. To do this, use the composer update command. This command checks all the dependencies defined in the composer.json file and looks for updates. This way, your dependencies will always be up-to-date.

Getting Help

By typing only composer without any parameters, you’ll see a list of available commands. You can update the list of repositories with selfupdate. You can also get help for a specific command using the word help before the command, for example, composer help require.

Related posts

6 Thoughts to “Composer: the PHP dependencies manager”

  1. Guilherme Rodrigues

    Quando vou instalar no windows , aparece o seguinte erro,

    Algumas configurações em seu aparelho faça Compositor incapaz de funcionar adequadamente .

    Certifique-se de corrigir os problemas listados abaixo e executar este script novamente :

    A extensão OpenSSL está faltando , o que significa que as transferências HTTPS seguras são impossíveis.

    Se possível, você deve habilitá-lo ou recompilar o PHP com –with- openssl

    pode me ajudar?

    1. Olá. Você precisa habilitar a extensão openssl no php.ini

      1. Guilherme Rodrigues

        Entao quando instalo o composer direcionando pra pasta do wamp , da certo , mas quando direciono pra pasta por ex “php” onde tem o php.exe que esta no path , n da certo msm que eu tenha habilitado o openssl no php.ini

        1. O que quer dizer com “redirecionar para a pasta”? O Composer deve ficar disponível como um comando no terminal, independente da pasta onde você está

          PS: não recomendo usar Wamp nem qualquer outro pacote. Prefira usar o PHP do site oficial

  2. Consegui instalar o Composer utilizando esse comando curl .
    Primeiro eu tive que no XAMPP conectar o Apache e o MySQL, para ativar o PHP, depois disso feito eu abri a janela do shell do XAMPP e digitei o comando do curl que funcionou e instalou o Composer dentro do XAMPP.
    Antes de fazer isso o comando curl não funcionava.

    1. o “curl” é um comando do sistema operacional, independente do PHP. Mas é usado o comando “php” para criar o arquivo compose.phar. Provavelmente foi por causa do comando “php” que você teve que fazer esses ajustes no Xamp

Leave a Comment