Install PHP Composer on Ubuntu 22.04 | Easy Guide Steps

Posted on

Install PHP Composer on Ubuntu 22.04 | Easy Guide Steps

Install PHP Composer on Ubuntu 22.04 | Easy Guide Steps

In this guide from Orcacore, you’ll learn how to Install and Use PHP Composer on Ubuntu 22.04. According to the Composer website, Composer is a tool for dependency management in PHP. It allows you to declare the libraries your project depends on, and it will manage, install, and update those libraries for you. Setting up Install PHP Composer on Ubuntu 22.04 is a crucial step for any PHP developer.

To complete this guide on Ubuntu 22.04 PHP Composer Setup, you must log in to your server as a non-root user with sudo privileges and set up a basic firewall. To do this, you can follow our guide on Initial Server Setup with Ubuntu 22.04.

1. Install Required Packages For Ubuntu 22.04 PHP Composer

To install PHP and its dependencies on Ubuntu 22.04, first update your local package index with the following command:

sudo apt update

Now install the required packages with the following command:

sudo apt install php-cli unzip

When you are done, you can start to download and install Composer on Ubuntu 22.04.

2. Get Composer Installer on Ubuntu 22.04

The composer comes with an installer script written in PHP.

To download it, be sure you are in your home directory and run the following command to get the installer:

# cd ~
# curl -sS https://getcomposer.org/installer -o composer-setup.php

Here you need to get the latest hash from the composer page and store it in a shell variable with the following command:

HASH=`curl -sS https://composer.github.io/installer.sig`

You can use the following command to verify it:

echo $HASH

In your output you will see:

**Output**
55ce33d7678c5a611085589f1f3ddf8b3c52d662cd01d4ba75c0ee0459970c2200a51f492d557530c71c15d8dba01eae

Then, you need to verify that the installation script is safe to run. For this, you can use the following command:

php -r "if (hash_file('SHA384', 'composer-setup.php') === '$HASH') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"

You should see this in your output:

**Output**
Installer verified

Note: If in your output, you see the Installer corrupt, you need to download the installation script again and check that you are using the correct hash.

Then, repeat the verification process. When you have a verified installer, you can continue.

3. Ubuntu 22.04 PHP Composer Setup

Now you can download and install Composer globally on Ubuntu 22.04 with the following command:

sudo php composer-setup.php --install-dir=/usr/local/bin --filename=composer

In your output, you will see something similar to this:

**Output**
All settings correct for using Composer
Downloading...

Composer (version 2.5.1) successfully installed to: /usr/local/bin/composer
Use it: php /usr/local/bin/composer

You can test your installation with the following command:

composer

[Image of Composer output in terminal]

It means that the Composer was successfully installed on Ubuntu 22.04 and is available system-wide.

Note: If you want to have separate Composer executables for each project you host on this server, you can install them locally.

This method is also useful when your system user doesn’t have permission to install software system-wide.

To do this you can use the “php composer-setup.php” command.

Let’s see how to use Composer on Ubuntu 22.04.

4. Use Ubuntu 22.04 PHP Composer

To use Composer in your project, you will need a “composer.json” file.

This file tells Composer which dependencies it needs to download for your project, and which versions of each package are allowed to be installed. You don’t need to create this file manually. Composer offers an interactive way to create a new composer.json file based on the user’s input.

It is a good choice if you plan on sharing your project later as a public package on Packagist.

The purpose of this application is to transform a given sentence into a URL-friendly string – a slug.

First, create a directory for your project. here we call it slugify:

# cd ~
# mkdir slugify
# cd slugify

It is not required, but you can now run a Composer init command on Ubuntu 22.04 to create a detailed composer.json file for your project.

Our project’s only objective is to show how to install dependencies with Composer. We will use a simpler composer.json file that will be auto-generated when we require our first package.

Now you can search for the term slug on Packagist which can help you generate the slug. You will see results similar to this:

[Image of Packagist search results for "slug"]

You’ll see two numbers on the right side of each package in the list.

The number on the top shows how many times the package was installed via Composer. And the number on the bottom shows how many times a package was starred on GitHub.

Packages with more installations and more stars tend to be more stable.

You need a string-to-slug converter. As you can see in your search result, the cocur/slugify package is a good match.

Use Composer Require command

Now you know which package you want to install. You can run the following command to include it as a dependency and also generate the composer.json file for your project:

composer require cocur/slugify

[Image of Composer require command output]

As you can see in your output, PHP Composer automatically decides which version of the package to use.

Now you can check your project with the following command:

You will see that it contains two files the composer.json and the composer.lock, and a vendor directory.

ls -l
**Output**
total 12
-rw-r--r-- 1 root root   59 Jan 16 08:58 composer.json
-rw-r--r-- 1 root root 3114 Jan 16 08:58 composer.lock
drwxr-xr-x 4 root root 4096 Jan 16 08:58 vendor

The composer.lock file is used to store information about which versions of each package are installed.

Also, it 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.

You can check the version restriction. If you check the composer.json file on Ubuntu 22.04 you will see:

cat composer.json
**Output**
{
    "require": {
        "cocur/slugify": "^3.0"
    }
}

The caret (^) before the version number used by the auto-generated composer.json file is the recommended operator for maximum interoperability.

Here, it defines 3.0 as the minimum compatible version and allows updates to any future version under 4.0.

For more information about Composer version restrictions, you can visit the official documentation.

Let’s see how to load dependencies automatically with Composer.

5. Load Dependencies Automatically with Composer

Composer provides an autoload script that you can include in your project to get autoloading working for your project.

This file is automatically generated by Composer when you add your first dependency.

You only need to include the vendor/autoload.php file in your PHP scripts before any class instantiation.

Now open a new file named test.php with your favorite text editor, here we use vi editor:

vi test.php

Add the following code to the file:

<?php
require __DIR__ . '/vendor/autoload.php';

use CocurSlugifySlugify;

$slugify = new Slugify();

echo $slugify->slugify('Hello World, this is a long sentence and I need to make a slug from it!');

When you are done, save and close the file.

Now you can run the script with the following command:

php test.php

In your output you will see:

**Output**
hello-world-this-is-a-long-sentence-and-i-need-to-make-a-slug-from-it

Dependencies need an update when new versions come out.

Use the Composer update command on Ubuntu 22.04 to update your project dependencies to more recent versions:

composer update

If a new version is found and it’s compatible with the version restriction defined in the composer.json file, the Composer will replace the previous version installed.

Also, you can update one or more specific libraries with the following command:

composer update vendor/package vendor2/package2

Note: After you update your dependencies be sure to check the composer.json and the composer.lock files within your version control system. So that others can install these newer versions too.

Conclusion

At this point, you have learned to Install and Use PHP Composer on Ubuntu 22.04. Composer in Ubuntu 22.04 is a dependency manager for PHP, used to install and manage PHP libraries and frameworks. It helps developers handle package dependencies efficiently in PHP projects. Learning to Install PHP Composer on Ubuntu 22.04 is vital for modern PHP development.

Hope you enjoy it. You may also like these guides:

How To Install Podman on Ubuntu 22.04

Install Wekan Server on Ubuntu 22.04

Install and Configure Jekyll on Ubuntu 22.04

Alternative Solutions for Dependency Management in PHP on Ubuntu 22.04

While Composer is the dominant dependency manager for PHP, alternative approaches exist, though they might not offer the same level of features, community support, or ease of use. Here are two different ways to manage PHP dependencies on Ubuntu 22.04:

1. Using PEAR (PHP Extension and Application Repository):

PEAR is an older package manager for PHP, predating Composer. While it’s less popular now, it’s still a viable option for some projects, especially those that rely on older libraries or have specific reasons to avoid Composer.

  • Explanation: PEAR allows you to install PHP packages (called "PEAR packages") from a central repository. It handles dependency resolution and installation, similar to Composer, but with a different ecosystem and set of packages. It’s generally considered less flexible and has a smaller selection of available packages than Composer. However, it’s pre-installed on many PHP installations, making it readily available.

  • Installation and Usage: While often pre-installed, you might need to update PEAR:

    sudo apt install php-pear
    sudo pear upgrade PEAR

    To install a package, you would use:

    sudo pear install Package_Name

    For example, to install the Mail package:

    sudo pear install Mail

    To use the installed package in your PHP script, you would typically include it using require_once:

    <?php
    require_once 'Mail.php';
    
    // Use the Mail package here
    ?>
  • Limitations:

    • Smaller package selection compared to Composer.
    • Less active development and community support.
    • Can sometimes have conflicts with system-level PHP installations.
    • Global installations by default can lead to dependency conflicts between projects.

2. Manual Dependency Management (Without a Package Manager):

This approach involves manually downloading and including the required libraries in your project. This is generally not recommended for complex projects, but it can be suitable for very small, simple scripts with few dependencies.

  • Explanation: Instead of using a package manager to handle dependencies, you download the source code (e.g., from GitHub or the library’s website) and place it within your project directory. Then, you use require or include statements in your PHP code to load the necessary files. This puts the onus on you to manually track dependencies, version updates, and potential conflicts.

  • Example: Let’s say you want to use a simple image resizing library called "SimpleImage."

    1. Download the SimpleImage.php file from a source (e.g., a GitHub repository, or the library’s official website).
    2. Create a directory within your project called lib (or any other name you prefer) and place SimpleImage.php inside it.
    3. In your PHP script, include the library:

      <?php
      require_once 'lib/SimpleImage.php';
      
      $image = new SimpleImage('image.jpg');
      $image->resize(100, 100);
      $image->save('image_resized.jpg');
      ?>
  • Drawbacks:

    • Extremely tedious and error-prone for projects with more than a few dependencies.
    • Difficult to manage version updates. You have to manually check for new versions and replace the files.
    • High risk of dependency conflicts if different libraries require different versions of the same dependency.
    • Difficult to share your project, as others would need to manually download and configure all the dependencies.
    • No automated dependency resolution. You must manually ensure that all dependencies of your dependencies are also present.

In conclusion, while PEAR and manual dependency management are technically viable, Composer remains the preferred and most efficient method for managing dependencies in PHP projects, especially on Ubuntu 22.04. The ease of use, vast package ecosystem, and robust dependency resolution features of Composer make it the clear winner for most PHP development scenarios. For simple scripts, manual management might suffice, but for anything more complex, Composer is the recommended solution to Install PHP Composer on Ubuntu 22.04.

Leave a Reply

Your email address will not be published. Required fields are marked *