php-composer-gestion-de-dependencias-en-php

Composer: Dependency Management in PHP

  • 2 min

Composer is the PHP dependency manager and is responsible for installing the libraries a project needs.

Composer is PHP’s Dependency Manager. It is a tool installed on your computer (like git or node) that allows you to easily download, update, and manage libraries created by other developers.

Why do we need it?

Imagine you want to generate PDFs on your website. You have two options:

  1. Old Option: Write the code to create PDFs yourself (it will take months) or search for a zip online, download it, check which version it is, put it in a folder…
  2. Composer Option: You write a command and Composer downloads the best PDF library, connects it to your project, and monitors it for security updates.

The Key Files

When you use Composer, you will see three new elements appear in your project:

  • composer.json: This is the configuration file. It is your “shopping list”. Here you specify: “My project needs the phpmailer library version 6.0”.
  • The vendor/ folder: This is where Composer physically downloads the libraries. Do not edit its contents manually; Composer regenerates it.
  • composer.lock: This is an automatic file that “freezes” the exact installed versions. It guarantees that if your teammate downloads the project, they will have exactly the same library versions as you.

Basic Commands (Your Day-to-Day)

Everything is handled from the terminal (console).

A. Starting a project (init)

If you start a new project, this creates the composer.json file.

composer init
Copied!

B. Installing a new library (require)

Imagine you want to install Monolog (a famous library for creating logs). You don’t go to Google; you go to your terminal:

composer require monolog/monolog
Copied!

This downloads the library to the vendor folder and adds it to your composer.json automatically.

C. Installing existing dependencies (install)

If you download a project from GitHub that uses Composer, you’ll notice that the vendor folder is missing. To create it and download everything necessary, you run:

composer install
Copied!

It reads the composer.lock file and downloads everything identical to how it was originally.

The Official Repository: Packagist

Where does Composer get the libraries? From Packagist.org. It is the official directory. If you need to do something (e.g., “read Excel”), you go to Packagist, search for “excel”, and you’ll see the package name (e.g., phpoffice/phpspreadsheet) to execute composer require.

The vendor folder and git

The vendor/ folder is NEVER uploaded to GitHub/Git.

It is heavy and redundant. In your .gitignore file there should always be a line that says:

/vendor
Copied!

Your teammates only need the composer.json and the composer.lock file. They will run composer install on their machines and get their own vendor folder.