How to Install and Use Composer on an Ubuntu Cloud Server?

05-02-2024 02:10:22

Composer is a dependency management tool for PHP, designed to install the PHP components required for a project, as well as to manage and update these components. This guide will demonstrate the method of installing and using Composer on an Ubuntu 20.04 cloud server.

Begin by adding the third-party PHP software repository ondrej/php.

# sudo add-apt-repository -y ppa:ondrej/php

Install PHP and the necessary components.

# sudo apt update
# sudo apt install -y -q php8.0-{cli,mysql,gd,common,curl}
# sudo apt install -y -q unzip

The commands above install the PHP command line, MySQL driver, gd library, common components, curl components, and also the unzip component for decompression purposes.

Install Composer in the /usr/local/bin directory.

# sudo curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer

Check if Composer has been installed successfully.

$ composer
   ______
  / ____/___  ____ ___  ____  ____  ________  _____
 / /   / __ \/ __ `__ \/ __ \/ __ \/ ___/ _ \/ ___/
/ /___/ /_/ / / / / / / /_/ / /_/ (__  )  __/ /
\____/\____/_/ /_/ /_/ .___/\____/____/\___/_/
                    /_/
Composer version 2.1.3 2021-06-09 16:31:20

To install PHP components, use the composer require command. For instance, using the monolog component, upon successful execution, it will be installed in the vendor directory.

$ composer require monolog/monolog

To remove PHP components, use the composer remove command.

$ composer remove monolog/monolog

Composer uses two files to record dependencies and components: the composer.json file records user-defined components, including the name and version number of the components, while the composer.lock file records each downloaded component package.

Composer has the capability to update itself and can be updated to the latest version at any time by executing the following command.

# sudo composer self-update

To update all PHP components in a specific directory, execute the following command.

$ composer update

Composer is a powerful PHP dependency management tool that works in conjunction with the packagist software repository, allowing for the easy integration of third-party components into projects.