Installing Composer on Debian/Ubuntu
- Installing Composer
- Testing Composer
- Autoload dependencies
- Dependency management
In this article I will explain how to install Composer on a Debian/Ubuntu operating system. Composer is a dependency manager for the PHP programming language. You can use it to extract all the necessary PHP packages that your project depends on. I had difficulty installing and using Composer when I first encountered package dependencies. So I wrote a simple installation guide for Composer so that it is easy for beginners to understand. Composer 2.1.6 is the latest stable version available for installation.
This instruction was executed on operating systems: Debian 10, Debian 9, Ubuntu 20.10, Ubuntu 20.04, Ubuntu 19.10.
Before installing Composer, check the required software. It is recommended to update the list of repository packages by running the command in the terminal:
sudo apt-get update
Make sure that PHP is already installed on your operating system and has version 5.3.2 or higher by running the command in the terminal:
Install the curl utility by running the command in the terminal:
sudo apt-get install curl
Download Composer using curl:
curl -sS https://getcomposer.org/installer | php
Move the composer.phar file to the /usr/local/bin directory:
sudo mv composer.phar /usr/local/bin/composer
Let's find out the version of installed Composer by running the command in the terminal:
Now let's see how to use Composer in a project. Create the root directory of the project and go to it.
mkdir ~/www-project && cd ~/www-project
Then all the commands are executed at the root of your project.
We will use the guzzle package as an example. Install this package by running the command in the terminal:
composer require guzzlehttp/guzzle
During installation, the guzzle package is loaded with all its dependencies. Two composer.json and composer.lock files, as well as the /vendor directory, will be created in the project directory. Run the command in the terminal to see this:
You can add autoload of all dependencies to your code:
Let's create a testing.php file and add the following code to it:
<?php require 'vendor/autoload.php'; use GuzzleHttp\Client; echo (new Client())->get('https://www.google.com')->getStatusCode() . "\n"; // 200
This script will output the HTTP code of the page by running it in the terminal:
You may need the following commands to manage dependencies.
To install defined dependencies of your project, run the command in the terminal:
To update dependencies to their latest versions, run the command in the terminal:
To update only one dependency, specify the package name at the end:
composer update guzzlehttp/guzzle
To remove a specific dependency, run the command in the terminal:
composer remove guzzlehttp/guzzle
To regenerate the vendor/autoload.php file, run the command in the terminal: