Composer is a dependency manager for PHP, allowing you to manage your project’s libraries and packages effortlessly. If you’re developing PHP applications, Composer is an essential tool. This guide will show you how to install and use Composer on Ubuntu 20.04.
Prerequisites
Before you start, make sure you have the following:
- An Ubuntu 20.04 server.
- A user with sudo privileges.
-
PHP installed on your server. If PHP is not installed, you can do so by running:
sudo apt update sudo apt install php-cli unzip
Step 1: Install Composer
1.1 Update Your Package Manager
First, update the package manager cache:
sudo apt update
1.2 Download the Composer Installer
Next, download the Composer installer script using curl
:
curl -sS https://getcomposer.org/installer -o composer-setup.php
1.3 Verify the Installer
Verify that the installer matches the SHA-384 hash for the latest installer found on the Composer Public Keys/Signatures page. Replace <HASH>
with the latest hash:
HASH=`curl -sS https://composer.github.io/installer.sig`
php -r "if (hash_file('sha384', 'composer-setup.php') === '$HASH') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
If the output says “Installer verified”, you can proceed. If it says “Installer corrupt”, then the script should be redownloaded.
1.4 Install Composer
Run the installer script:
sudo php composer-setup.php --install-dir=/usr/local/bin --filename=composer
This command installs Composer globally, making it accessible from any directory.
1.5 Verify the Installation
To verify the installation, run:
composer --version
You should see output similar to:
Composer version 2.x.x 2021-xx-xx xx:xx:xx
Step 2: Using Composer
2.1 Create a PHP Project
Navigate to your project directory:
cd /path/to/your/project
2.2 Initialize a New Project
To start a new project, run:
composer init
Follow the prompts to set up your project’s composer.json
file.
2.3 Install Dependencies
To install a package (e.g., Monolog for logging), run:
composer require monolog/monolog
This command downloads and installs the package into the vendor
directory and updates composer.json
with the new dependency.
2.4 Update Dependencies
To update your project’s dependencies, run:
composer update
2.5 Autoloading
Composer provides an autoloader to manage your PHP classes. Include the following line at the beginning of your PHP scripts to use it:
require 'vendor/autoload.php';
Conclusion
You’ve now installed and configured Composer on your Ubuntu 20.04 server. Composer simplifies dependency management in PHP, making your development process more efficient. For more information on using Composer, check out the official Composer documentation.
Happy coding!
Source link
lol