Composer is a popular dependency management tool for PHP, created mainly to facilitate installation and updates for project dependencies. Composer works by checking which other packages a specific project depends on, and then installs them for you using the appropriate versions according to the project requirements. Composer is also commonly used to bootstrap new projects based on popular PHP frameworks such as Symfony and Laravel.
In this guide, you will install and use Composer on a Debian 11 server.
Prerequisites
To follow this tutorial, you will need one Debian 11 server set up, including a non-root sudo
-enabled user and firewall enabled. You can do this by following our Debian initial server setup guide.
Step 1 — Installing the Dependencies
In addition to dependencies that may already be included within your Debian 11 system, Composer requires php-cli
to execute PHP scripts in the command line, and unzip
to extract zipped archives.
Begin by updating the package manager cache:
Next, install the dependencies. You will need curl
to download Composer and php-cli
for installing and running it. The php-mbstring
package is necessary to provide functions for a library you’ll be using in this tutorial. git
is used by Composer for downloading project dependencies, and unzip
is for extracting zipped packages. Everything can be installed with the following command:
With all the dependencies installed, now you can install Composer.
Step 2 — Downloading and Installing Composer
Composer provides an installer written in PHP. You will download it, verify that it’s not corrupted, and then use it to install Composer.
First, make sure you’re in your home directory:
Then, retrieve the installer using curl
:
Next, verify that the installer matches the SHA-384 hash for the latest installer found on the Composer Public Keys / Signatures page. To facilitate the verification step, you can use the following command to programmatically obtain the latest hash from the composer page and store it in a shell variable:
To output the obtained value, run:
55ce33d7678c5a611085589f1f3ddf8b3c52d662cd01d4ba75c0ee0459970c2200a51f492d557530c71c15d8dba01eae
Now execute the following PHP code, as provided in the Composer download page, to verify that the installation script is safe to run:
Your output will be the following:
Installer verified
If you receive a message that says Installer corrupt
, you need to download the installation script again and verify that you’re using the correct hash. Then run the command to verify the installer again. Once you have a verified installer, you can continue.
To install composer
globally, use the following command to download and install Composer as a system-wide command named composer
under /usr/local/bin
:
Your output will be the following:
All settings correct for using Composer
Downloading...
Composer (version 2.3.10) successfully installed to: /usr/local/bin/composer
Use it: php /usr/local/bin/composer
Test your installation by running this command:
Your output will then display Composer’s version and arguments, similar to the following:
______
/ ____/___ ____ ___ ____ ____ ________ _____
/ / / __ \/ __ `__ \/ __ \/ __ \/ ___/ _ \/ ___/
/ /___/ /_/ / / / / / / /_/ / /_/ (__ ) __/ /
\____/\____/_/ /_/ /_/ .___/\____/____/\___/_/
/_/
Composer version 2.3.10 2022-07-13 15:48:23
Usage:
command [options] [arguments]
Options:
-h, --help Display help for the given command. When no command is given display help for the list command
-q, --quiet Do not output any message
-V, --version Display this application version
--ansi|--no-ansi Force (or disable --no-ansi) ANSI output
-n, --no-interaction Do not ask any interactive question
--profile Display timing and memory usage information
--no-plugins Whether to disable plugins.
--no-scripts Skips the execution of all scripts defined in composer.json file.
-d, --working-dir=WORKING-DIR If specified, use the given directory as working directory.
--no-cache Prevent use of the cache
-v|vv|vvv, --verbose Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug
. . .
This verifies that Composer was installed successfully on your system and is available system-wide.
Note: If you prefer to have separate Composer executables for each project you host on this server, you can install it locally, on a per-project basis. Users of NPM will be familiar with this approach. This method is also useful when your system user doesn’t have permission to install software system-wide.
To do this, use the command php composer-setup.php
. This will generate a composer.phar
file in your current directory, which can be executed with ./composer.phar command
.
Now that you’ve installed Composer, in the next step you will learn how to use Composer to manage PHP dependencies.
Step 3 — Using Composer in a PHP Project
PHP projects often depend on external libraries, and managing those dependencies and their versions can be tricky. Composer solves that issue by tracking your dependencies and making it more accessible for others to install them.
In order to use Composer in your project, you’ll need a composer.json
file. The composer.json
file tells Composer the dependencies it needs to download for your project, and the versions of each package that are allowed to be installed. This is extremely important to keep your project consistent and avoid installing unstable versions that could potentially cause backward compatibility issues.
You don’t need to create this file manually, because doing so is error prone and may cause syntax errors. Composer auto-generates the composer.json
file when you add a dependency to your project using the composer require
command. You can add additional dependencies in the same way, without the need to manually edit this file.
The process of using Composer to install a package as a dependency in a project involves the following steps:
- Identify what kind of library the application needs.
- Research a suitable open-source library on Packagist.org, the official package repository for Composer.
- Choose the package you want to depend on.
- Run
composer require
to include the dependency in thecomposer.json
file and install the package.
You can test this out with a demo application.
The goal of this application is to transform a given sentence into a URL-friendly string called a slug. A slug is commonly used to convert page titles to URL paths, such as the final portion of the URL for this tutorial.
Start by navigating to your home directory:
Then create a directory. Call it slugify
:
After you’re done creating it, change into the directory:
Now it’s time to search Packagist.org for a package that can help generate slugs. If you search for the term “slug” on Packagist, you’ll get a result similar to the following:
There will be two numbers on the right side of each package in the list. The number next to the icon with the arrow pointing down represents how many times the package was installed, and the number with the star icon represents how many times a package was starred on GitHub. You can also reorder the search results based on these numbers. Generally speaking, packages with more installations and more stars tend to be more stable, since so many people are using them. It’s also important to check the package description for relevance to make sure it’s what you need.
For this tutorial, you need a string-to-slug converter. From the search results, the package cocur/slugify
is a good match, with a reasonable amount of installations and stars.
Packages on Packagist have a vendor name and a package name. Each package has a unique identifier (a namespace) in the same format GitHub uses for its repositories, in the form vendor/package
. The library you want to install uses the namespace cocur/slugify
. You need the namespace in order to require the package in your project.
Now that you know the package you want to install, run composer require
to include it as a dependency and also generate the composer.json
file for the project:
Your output will return the following as Composer downloads the dependency:
Using version ^4.1 for cocur/slugify
./composer.json has been created
Running composer update cocur/slugify
Loading composer repositories with package information
Updating dependencies
Lock file operations: 1 install, 0 updates, 0 removals
- Locking cocur/slugify (v4.1.0)
Writing lock file
Installing dependencies from lock file (including require-dev)
Package operations: 1 install, 0 updates, 0 removals
- Downloading cocur/slugify (v4.1.0)
- Installing cocur/slugify (v4.1.0): Extracting archive
Generating autoload files
As this output indicates, Composer automatically decides the version of the package to use. If you check your project’s directory now, it will contain two new files: composer.json
and composer.lock
, and a vendor
directory:
Output
total 12
-rw-r--r-- 1 sammy sammy 59 Aug 2 22:19 composer.json
-rw-r--r-- 1 sammy sammy 3462 Aug 2 22:19 composer.lock
drwxr-xr-x 4 sammy sammy 4096 Aug 2 22:19 vendor
The composer.lock
file is used to store information about the versions of each installed package. It also ensures the same versions are used if someone else clones your project and installs its dependencies. The vendor
directory is where the project dependencies are located. The vendor
folder doesn’t need to be committed into version control, you only need to include the composer.json
and composer.lock
files.
When installing a project that already contains a composer.json
file, run composer install
in order to download the project’s dependencies.
Next, review the version constraints. If you check the contents of your composer.json
file, you’ll have something like the following:
You might notice the special character ^
before the version number in composer.json
. Composer supports several different constraints and formats for defining the required package version, in order to provide flexibility while also keeping your project stable. The caret (^
) operator used by the auto-generated composer.json
file is the recommended operator for maximum interoperability, following semantic versioning. In this case, it defines 4.1 as the minimum compatible version and allows updates to any future version under 5.0.
Generally speaking, you won’t need to tamper with version constraints in your composer.json
file. However, some situations might require that you manually edit the constraint. For instance, when a major new version of your required library is released, and you want to upgrade, or when the library you want to use doesn’t follow semantic versioning.
Here are some examples to give you a better understanding of how Composer version constraints work:
Constraint | Meaning | Example Versions Allowed |
---|---|---|
^1.0 | >= 1.0 < 2.0 | 1.0, 1.2.3, 1.9.9 |
^1.1.0 | >= 1.1.0 < 2.0 | 1.1.0, 1.5.6, 1.9.9 |
~1.0 | >= 1.0 < 2.0.0 | 1.0, 1.4.1, 1.9.9 |
~1.0.0 | >= 1.0.0 < 1.1 | 1.0.0, 1.0.4, 1.0.9 |
1.2.1 | 1.2.1 | 1.2.1 |
1.* | >= 1.0 < 2.0 | 1.0.0, 1.4.5, 1.9.9 |
1.2.* | >= 1.2 < 1.3 | 1.2.0, 1.2.3, 1.2.9 |
Next, you will learn how to load dependencies automatically with Composer.
Step 4 — Including the Autoload Script
Since PHP itself doesn’t automatically load classes, Composer provides an autoload script that you can include in your project to get autoloading to work. This helps when working with your dependencies.
The only thing you need to do is include the vendor/autoload.php
file in your PHP scripts before any class instantiation. This file is automatically generated by Composer when you add your first dependency.
You can test it out in your application. Create the file test.php
and open it in your preferred text editor. Here, nano
is used:
Add the following code to bring in the vendor/autoload.php
file, load the cocur/slugify
dependency, and create a slug:
Save the file and exit your editor. If you’re using nano
, you can do this by pressing CTRL + X
, then Y
and ENTER
.
Now run the script:
This produces the following output:
hello-world-this-is-a-long-sentence-and-i-need-to-make-a-slug-from-it
Dependencies need updates when new versions come out, so you will learn how to handle that in the last step.
Step 5 — Updating Project Dependencies
Whenever you want to update your project dependencies to more recent versions, run the update
command:
This will check for newer versions of the libraries you added as requirements in your project. If a newer version is found and it’s compatible with the version constraint defined in the composer.json
file, Composer will replace the previous version installed. The composer.lock
file will be updated to reflect these changes.
You can also update one or more specific libraries by specifying them like the following:
Be sure to commit the changes to your composer.json
and composer.lock
files after you update your dependencies, so whoever is working in the project has access to the same package versions.
Conclusion
Composer is a powerful tool every PHP developer should have in their utility belt. In this tutorial, you installed Composer on Debian 11 and used it in a project. You now know how to install and update dependencies.
Beyond providing a reliable way for managing project dependencies, Composer also establishes a new standard for sharing and discovering PHP packages created by the community.