Composer is a cross-platform tool for managing dependencies in projects written in PHP.
With Composer, you can manage numerous libraries and frameworks, known as "packages." Installing the required packages allows you to extend the standard PHP functionality, speeding up and simplifying development. All installed packages become project dependencies.
Thus, Composer can be considered a full-fledged dependency manager, similar to those used in many programming languages.
Additionally, Composer has a comprehensive package repository called Packagist, where you can search for, download, and install the required packages.
This guide provides detailed instructions on installing Composer on an Ubuntu server and using it for PHP projects.
In this tutorial, we use:
First, update the list of existing APT repositories:
sudo apt update
Next, install the packages required to download and use Composer:
sudo apt install curl php-cli unzip -y
These packages include:
curl
: A tool for making HTTP requests.php-cli
: An interpreter to run PHP scripts.unzip
: A utility to extract ZIP archives.The -y
flag answers "yes" to all installation prompts.
Composer installation is automated using a PHP script provided by its developers.
Download the installation script from the official Composer website using an HTTP request:
curl -sS https://getcomposer.org/installer -o composerInstall.php
-sS
flag runs curl
in silent mode, suppressing all output except for errors.-o
flag specifies the filename and the directory where the file will be placed.To ensure the file has been downloaded, check the contents of the current directory:
ls
You should see the following output in the terminal, including the installation script:
composerInstall.php resize.log snap
This guide covers the global installation of Composer, meaning it can be run from any directory without specifying the absolute path.
To perform a global installation, execute the downloaded PHP script with additional parameters:
php composerInstall.php --install-dir=/usr/local/bin --filename=composer
--install-dir
flag specifies the directory where Composer will be installed.--filename
flag defines the name of the binary file accessible from the terminal.In this case, Composer is installed in the system's binary directory: /usr/local/bin
.
After running the script, you'll see the following output in the terminal:
All settings correct for using Composer
Downloading...
Composer (version 2.8.2) successfully installed to: /usr/local/bin/composer
Use it: php /usr/local/bin/composer
Since the installation script is no longer needed, you can delete it:
rm composerInstall.php
To launch Composer for the first time, run:
composer
You may see the following message in the terminal:
Do not run Composer as root/super user! See https://getcomposer.org/root for details
Continue as root/super user [yes]?
Composer warns against running it as the root user due to potential risks but allows you to proceed.
For this guide, we will continue using Composer as-is by confirming with yes
.
Afterward, you will see a welcome message along with a list of available options and commands with brief descriptions.
Composer is now fully installed.
The main file used to manage dependencies is composer.json, which describes the packages required for the proper functioning of a project.
Composer follows the Infrastructure as Code (IaC) approach, describing the local project infrastructure through a configuration file rather than manual settings adjustments in a graphical interface.
However, Composer allows configuration management not only by manually editing the file in a text editor but also through console commands, providing a more interactive way to handle configurations.
Using Composer involves several fundamental commands that interact with the composer.json configuration file:
init
: Initializes a project.require
: Adds a package.install
: Installs dependencies.update
: Updates packages.Although Composer offers many more commands, these are the most frequently used.
Create a separate directory for the PHP project:
mkdir phptest
Then navigate to the directory:
cd phptest
This directory will store both the project’s source code and the required dependency files.
Suppose we are working on a small project that performs various string transformations. As a dependency, we need a specific library that provides functions for manipulating string content.
In this guide, we will implement a common programming function called slugify
, which converts a sequence of words into a single long word containing only lowercase ASCII characters and hyphens.
The slugify
function is often used to transform arbitrary headings into URL-friendly formats without spaces.
Rather than writing this function ourselves, we will use Composer to find a suitable library in the official package registry, add it as a dependency, and let Composer handle its download, installation, and integration into the project.
To find the necessary library, follow these steps:
The search results display key metrics for each available package:
In general, popular packages tend to be more stable since they are used by a larger number of developers.
In this guide, we will use the package cocur/slugify.
The package name, similar to a GitHub repository, contains the author (provider) and the library name separated by a forward slash (/).
We can navigate to the package's page by clicking its name to see more details about the library’s implementation, such as dependency lists, descriptions with code examples, test coverage badges, license type, and more.
Additionally, pay attention to the available package versions, as you need to specify the version during dependency installation.
By following this process, you can search for and select suitable packages for a PHP project, which can later be used as dependencies to provide specific functions.
To install the required package, use the require
command. This either records the dependency in the composer.json
configuration file or creates it if it does not exist:
composer require cocur/slugify:4.6
In this guide, we are using cocur/slugify
version 4.6.0.
After running the command, you might encounter an error indicating missing system libraries:
./composer.json has been created
Running composer update cocur/slugify
Loading composer repositories with package information
Updating dependencies
Your requirements could not be resolved to an installable set of packages.
Problem 1
- Root composer.json requires cocur/slugify 4.1 -> satisfiable by cocur/slugify[v4.1.0].
- cocur/slugify v4.1.0 requires ext-mbstring * -> it is missing from your system. Install or enable PHP's mbstring extension.
This console output informs us that the ext-mbstring
system library is missing, which is necessary for cocur/slugify
to work correctly.
You can manually search for the library using the APT package manager:
sudo apt search mbstring
The search results will show:
Sorting... Done
Full Text Search... Done
php-mbstring/jammy 2:8.1+92ubuntu1 all
MBSTRING module for PHP [default]
php-patchwork-utf8/jammy 1.3.1-1 all
UTF-8 strings handling for PHP
php-symfony-polyfill-mbstring/jammy 1.24.0-1ubuntu2 all
Symfony polyfill for the Mbstring extension
php-symfony-polyfill-util/jammy 1.24.0-1ubuntu2 all
Symfony utilities for portability of PHP codes
php8.1-mbstring/jammy-updates,jammy-security 8.1.2-1ubuntu2.19 amd64
MBSTRING module for PHP
The first result is the library we need. Install it with:
sudo apt install php-mbstring -y
Once the missing library is installed, rerun the command to install the package:
composer require cocur/slugify:4.6
This time, the console output should confirm a successful installation:
./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.6.0)
Writing lock file
Installing dependencies from lock file (including require-dev)
Package operations: 1 install, 0 updates, 0 removals
- Downloading cocur/slugify (v4.6.0)
- Installing cocur/slugify (v4.6.0): Extracting archive
Generating autoload files
No security vulnerability advisories found.
Check the directory contents with:
ls
You will see new files generated by Composer:
composer.json composer.lock vendor
Each file and directory serves a specific purpose:
composer.json
— Contains information about the required dependenciescomposer.lock
— Records details about installed dependenciesvendor
— Stores the project’s installed dependenciesIf you use a version control system like Git, exclude the vendor directory from the repository.
Take a look inside composer.json
:
cat composer.json
It should look like this:
{
"require": {
"cocur/slugify": "4.6"
}
}
You’ll notice the require
block specifying the package cocur/slugify
version 4.6. You can find more detailed information about possible version values in the official Composer documentation.
Once you have installed a dependency, you can include it in the project code using the automatically generated autoload.php
script, located in the vendor directory.
When this script is included in the PHP application, the functions and classes of the installed dependencies become available for use.
Let's create the main file of our application:
sudo nano main.php
Then, fill it with the following content:
<?php
require __DIR__ . '/vendor/autoload.php';
use Cocur\Slugify\Slugify;
$slugify = new Slugify();
// PHP_EOL is needed for line breaks in the console
echo '[english]: ' . $slugify->slugify('How to deal with composer') . PHP_EOL;
?>
Now, you can run the script:
php main.php
The output in the console terminal should look like this:
[english]: how-to-use-composer
Composer allows you to check for new versions of libraries based on version ranges defined in the composer.json
configuration file:
composer update
Alternatively, you can update a specific package by specifying its name:
composer update cocur/slugify
If your PHP project contains a composer.json
file, but the specified dependencies are not yet installed, you need to install them.
Let’s first remove all existing packages and related information:
rm -R vendor composer.lock
The -R
flag is necessary for recursive deletion of files and directories.
After that, try running the script:
php main.php
You will see the expected error message in the console because the dependencies are missing:
PHP Warning: require(/root/phptest/vendor/autoload.php): Failed to open stream: No such file or directory in /root/phptest/main.php on line 2
PHP Fatal error: Uncaught Error: Failed opening required '/root/phptest/vendor/autoload.php' (include_path='.:/usr/share/php') in /root/phptest/main.php:2
Stack trace:
#0 {main}
thrown in /root/phptest/main.php on line 2
Now, let's reinstall the dependencies based on the data from the configuration file:
composer install
After that, run the script again:
php main.php
The console should display the expected result without any errors:
[english]: how-to-install-and-use-composer
You can install Composer on Ubuntu 22.04 automatically using an installation script from the official Composer website.
Although Composer has many commands to manage the composer.json
configuration file, in practice, only a few basic ones are commonly used:
composer init
composer require
composer install
composer update
You can find comprehensive information on how to use Composer in the official documentation.