Composer tool featured image

 Installing and Using Composer on Ubuntu 18.04

Composer is a popular PHP dependency management tool. It is primarily leveraged to assist in project dependency updates and installation. It works by checking and verifying the versions of other packages that are appropriate for project requirements and dependencies and installing them for your convenience. In this tutorial, we will walk you through the steps of installing Composer on Ubuntu 18.04.

In order to be able to follow the tutorial make sure that you have already configured a non-root user with sudo privileges on the local server. To help you with that take a look at our tutorial on configuring the Linux sudoers file. In addition, you have to enable your basic firewall and block the nonessential ports. Here is a tutorial on setting up a UFW on Ubuntu and Debian cloud server. Before you start the installation, log into your non-root user with privileges. You can easily install your server by following our tutorial on setting up an Ubuntu server. Now, let’s start!

Dependencies Installation

Prior to installing Composer, you should verify that all of the necessary dependencies are installed. You can start by updating the packet manager. You can do this by running:

Next, we can install the dependencies. To do so, you will need curl to download Composer and php-cli to install and run it. Necessary functions for the library which we will utilize need the php-mbstring package, git will download project dependencies, and extraction of zipped files required to unzip. All of these can be installed with just one command. It is as follows:

Once the prerequisite installations are handled, we can move on to installing Composer.

Composer Download and Installation

We will download the Composer installer, verify that there is no corruption, and then install it. After making certain that you are in your home directory, you should use curl to get the installer:

Using the Composer keys and signatures page, we will need to ensure that the installer matches the SHA-384 of the latest available version. To do so, we will copy that hash from that page. Then, we have to store it in the form of a shell variable with the latest hash in place of the following example:

Next, verify that the installation script is safe to run by executing the following PHP script:

This should return:

installer verification

If the returned output includes Installer corrupt, you will need to download the installation script over. Then, you need to verify that you are using the right hash. At this point you can run the verification command again. Once the verification is successful, you can proceed.

To install composer globally, you can use the following sudo command. This will install Composer as a command on a system-wide level named composer. It will be installed under /usr/local/bin:

After running it, the following output will appear:

composer setup

Let’s verify that the installation was successful by launching Composer:

This will display the following version and argument information about Composer:

composer info

Note: Composer can also be installed locally if you prefer to have separate executables for each project hosted on this server. This is similar to the approach used for NPM and is a useful method when the system does not permit the installation of system-wide software. This can be using the php composer-setup.php command, which will create a composer.phar in the current directory, and can be executed using the command: ./composer.phar.

 

Next, we’ll look at managing dependencies using Composer.

Utilizing Composer for PHP Projects

Very often, PHP projects rely on external libraries. This creates a challenge in managing versions and dependencies. Composer helps to ease the process by tracking the dependencies, simplifying others’ installations of them.

You will need a composer.json file to use Composer for your project. This file will serve as a roadmap for Composer. It will inform it about which dependencies still need to be downloaded, as well as which package versions will be allowed to be installed. This is an essential component of mitigating the use of unstable versions and keeping the project consistent. Outdated or unstable versions could create backward compatibility problems.

Since creating the file manually is tough to do without running into syntax issues, the file is autogenerated by Composer once you use a require command to add a dependency to your project. Other dependencies can be added similarly without needing to manually edit the file.

The installation of a package with Composer as a dependency for a project can be done as per the following:

  • Identifying the library needed by the application.
  • Look through Packagist.org, Composer’s official package repository to research the appropriate open-source library.
  • Choose the appropriate dependency package.
  • Include the dependency in the composer.json file by running the composer require command.

Let’s presuppose that we have an application with the goal of converting a sentence provided into a slug (a URL-friendly string), something commonly utilized to convert page titles into URL paths. We will first need to create a project directory. For the sake of this example, we will label it as slugify:

Next, we will need to search Packagist.org for the package that can help us form slugs. You should query the term “slug” and observe the results:

slug package search

The list will have two numbers in the right column of each listed package. The top number represents the amount of downloads for that particular package. The bottom number shows how many times a package was starred on GitHub. These results can be sorted based on the ascending or descending order of either of those two numbers. The packages with both numbers on the high end are used by more people, meaning that they are more likely to be stable. However, it is still vital to thoroughly read the descriptions of the packages to make certain the package contains what you require.

As stated, for this example, we need only to locate a converter from string to slug. We can see that the package cocur/slugify seems to have a respectable download and star number, with a description fitting our needs. The Packagist package choices will all have a package name and a vendor name associated with them. GitHub uses a vendor/package format to set up identifiers for each package, with Packagist following the same formatting schematic. The package we are looking to install is cocur/slugify so we will need to retain that name in order to require the package. Once the package to install is formally identified, we will need to run composer require to link it to the compose.json file as a dependency:

Composer will return the following dependency:

download slugify

You will note that Composer has detected and determined the appropriate version of the package automatically. After this, the project’s directory will contain two new files (composer.json and composer.lock) and a vendor directory.

list composer files

The information about the package versions will be stored in the composer.lock file. This will also be used to ensure that if anyone else clones your project, they will be using the same dependency versions. The dependencies will be placed in the vendor directory, but that folder will not need to be committed to version control. Only composer.json and composer.lock files will need to be included.

Note: If a project already has a composer.json file, composer install should be run to install dependencies for the project.

Version constraints should also be taken under consideration. Looking at the composer.json file, you will see something resembling this:

composer.json

Ahead of the version number in composer.json you will note there is a special character (^). Since Composer offers additional flexibility and support for a variety of formats and constraints when the package version is defined to ensure project stability, the caret (^) is auto-generated by composer.json file to allow for interoperability power after semantic versioning. With the above example, version 3.1 is defined as being a minimal requirement to allow compatibility, but any version up to 4.0 is allowed to be updated to.

It is unlikely that any adjustments will be required to version numbers, but certain situations might require tampering with this constraint. For instance, if a new version of the library does not follow semantic versioning or when a major new version is a mandated requirement.

To better understand how Composer constraints function, note the following chart:

Composer constraints function

More details about Composer’s version constraints can be found in their official documentation. We will now turn our focus to loading dependencies with Composer automatically.

Autoload Scripting Inclusion

To make working with dependencies easier and because PHP does not offer a way to load classes automatically, Composer includes a script that can be included in a project to autoload the necessary dependencies for free.

Before establishing any class, you just need to make sure to include the vendor/autoload.php file as part of your PHP scripts. Composer will automatically generate this file as the initial dependency is added. We will test this by creating a test.php file and opening it in a text editor:

We then need to add the following code that pulls in the vendor/autoload.php file, sets the concur/slugify dependency, in order to create a slug:

Next,  we will save the file, close down the text editor, and run the script via:

This will generate the following output:

test.php output

When newer versions are released, dependencies will/might require updates. Next, we will look into how to do this.

Dependency Updates

To update project dependencies to the most recent versions, we can use the update command in the following manner:

This will check your project against the newer versions that it requires, and if one is found to be compatible, Composer will replace the prior version according to the version constraints as defined in the composer.json file. Alongside this, the composer.lock file will also be updated with these changes. Specific libraries can also be updated in this manner:

After updating the dependencies, you will want to make sure to check out the composer.json and composer.lock files to ensure that other users can also install newer versions.

Conclusion

Composer is one of PHP’s most powerful tools. This guide helped you install Composer and illustrated how to use it for a basic project, along with illustrating how dependencies are installed and updated. Aside from allowing for a simple and reliable method to manage project dependencies, Composer sets up a new standard in how community-created PHP packages are discovered and shared.

Here are some more resources on PHP tools that you might find useful:

Happy Computing!