PHP

How to Install and Use Composer

Introduction

One of the many mind-numbing issues web developers face has to do with dependencies. We’ve all been in situations where integrating new packages in our projects causes more trouble than needed.

This issue is especially frequent for PHP developers. It is common to find programmers constantly building modules such as data persistence from the ground-up. The result is an enormous waste of resources on redundant tasks – tasks that could otherwise be handled by already existent solutions.

Enter Composer – a sleek and simple dependency manager for PHP. Some of you might already be familiar with similar dependency managers like PIP for Python or NPM for Node.js. Simply put, Composer will streamline all of your project’s dependencies in a single place.

A neat feature of Composer, which separates it from other dependency management solutions like PEAR, is the ability to resolve dependencies on a per project basis. Composer manages dependencies for each of your projects separately. This means that you will not have libraries in your projects which are not being used – a bonus in terms of keeping the project size in check.
Having said that, you can install packages system-wide by using Composer. This is done through a special global command, but we won’t get into that in this guide for the purposes of simplicity and ease.

In this tutorial, you will learn how to install Composer and use it in your future PHP projects. Simply follow this step by step guide, and you should be good to go.

What you’ll need

Before you begin this guide, you’ll need the following:

  • Access to the command line interface

Step 1 – Installing Composer

The first and the easiest step is installing Composer on your system. Here you will find Composer installation guides for both Linux and Windows, and will even find out how to install it on Hostinger’s shared hosting. Mac users need not despair; just open up your terminal and follow the Linux guideline. Three different ways to install Composer are listed below.

Option 1 – Installing Composer on Hostinger Shared Hosting

IMPORTANT: Composer is now pre-installed on Hostinger premium and business plans. If you are using Hostinger shared hosting, you can skip this part and proceed with Generating and Understanding composer.json step.

You can install and run Composer on Hostinger Premium and Business plans with ease! We will use a script in order to automatically download and install the latest Composer version:

  1. Firstly you need to connect to your hosting account via SSH. You can find the instructions on how to do that here.
  2. Now create a new file using nano text editor and name it composer-installer.sh:
  3. The above command will open nano text editor. Paste the script below:
    This script will download the latest Composer version, check its signature and proceed with the installation if the signature is valid.
  4. Save changes and exit nano text editor by pressing CTRL (CMD for MacOS) + X keys, Y and ENTER keys.
  5. Now execute the script with the following command:
  6. If the installation has been successful, you will not see any output. To confirm that Composer installation is successful, enter:
  7. You should see an output simillar to this:

As we can see from the output above, Composer has been successfully installed!

Option 2 – Installing Composer on Linux/MacOS

Most PHP developers use either their Macs or Linux-based operating systems for development, making this section relevant to the majority of readers. The process is very similar on both OS. You have to run the same commands on your system’s terminal in order to get Composer.

Note: For the sake of learning, in this option we will use separate commands instead of script. Part of these commands will change every time a new version of Composer is released. Thus, be sure to check this page before proceeding futher.

There are two options for Linux/Mac users when installing Composer:

Local Installation

Not the most common option, but you can choose to install Composer locally. This means that your operating system will not be able to run Composer from anywhere; you will have to specify the path from where it is installed. To do this, follow these steps:

  1. Open your terminal or connect to your server via [SSH]]({{ site.baseurl }}{% post_url 2016-08-27-how-to-connect-to-your-vps-using-putty %}).
  2. Run the two following commands:
    The first command will grab the Composer installer as a PHAR (PHP Archive) file, while the second ensures that the installer is free from any errors or corruption. After executing these commands, you will have the latest build of Composer’s installer on your drive.
  3. Install Composer via the command:
    You can change the installation directory and filename through the –install-dir and –filename parameters. Here you can see that the directory has been named bin, and the executable is installed by the name composer.
  4. Now that you’ve installed Composer, you can run it by typing the following command:

Global Installation

After the local installation, we recommend making Composer accessible globally. This will ensure that Composer can be executed from anywhere on your system, regardless of the path. We do this by adding Composer to your PATH variable.

To do this, you have to:

  1. Follow the instructions given in Local Installation.
  2. Run the following command afterwards:
    Now you can boot Composer independent of your current path in the terminal.
  3. To run Composer, execute the command:

Congratulations! You have successfully installed Composer on your system.

Option 3 – Installing Composer on Windows

Like most other program installations, getting started with Composer is much simpler on a Windows machine. No command line instructions are necessary for downloading and installing Composer. Simply follow these steps:

  1. Download the latest Composer version from here.
  2. Once downloaded, simply run the wizard and install Composer. Process is straight forward and it should not take more than a few minutes.
    Composer Install Wizard Windows
  3. After completing the installation, open the command prompt. To open it, press CTRL +R, type in cmd and press the OK button.
    Windows Run
  4. In the command prompt, type the following:

Voila! You have installed Composer on your Windows computer. The installer automatically takes care of adding Composer to your PATH variable. You can open up the command prompt and run Composer from anywhere.

Step 2 – Generating and Understanding composer.json

Now comes the interesting part – using Composer for the first time in your PHP project. To achieve this, you need to generate a composer.json file for the project. This file can be thought of as a lookup list for Composer; it will only download those packages (dependencies) for your project that are mentioned in this file.

Note that it also checks for version compatibility of the packages with your project. This means that if you are using an older package in your project, the composer.json file will let you know in order to avoid any future inconvenience.
You also have the option to create and update the composer.json file yourself. But seeing that this is a tutorial on automating redundant tasks, it might be slightly ironic for you to create the file manually.

Let’s demonstrate the usefulness of composer.json by creating a sample project. Our project is a simple PHP timer, for developers wanting to find how much time a specific piece of code takes to execute. This is highly useful for debugging and optimization purposes. To do this, follow these steps:

  1. Create a new directory for the project. As our project is a timer, we’ll name it, quite unimaginatively, phptimer. To achieve this, open the terminal, and type the following command:
  2. Enter the newly created directory via the command:
  3. Now you need a package or library which has already implemented a timer in PHP. The best place to find Composer packages is on Packagist – the official destination for packages built for Composer. Here you’ll find all sorts of libraries to shoulder some of your development burden. For the sake of this tutorial, we need a timer package/library. To do this, simply type ‘timer’ in the search bar, like this:
    Packagist Search
  4. As you can see, a number of timers are available for developers on the site. Each package has a name and a small description of what it does. In front of each package is the download count, as well as its GitHub star count. Let’s go with phpunit/php-timer (7th entry in the list) as it has the most downloads and most GitHub stars. Note that each package is in the following format:
    vendor/package [phpunit/php-timer]
    This is also called the namespace. The namespace has to be unique for each package on Packagist, as it is used to identify different packages.
  5. After deciding on which package to install, you simply need to notify Composer of your choice, so it can add it to your project. To do this, type the following command in the terminal:

After executing the above command, Composer will create two new files (composer.json and composer.lock) in your project directory, in addition to a new folder named vendor.

The vendor directory is where Composer will store all of your packages and dependencies. This is useful for some people, if they want to copy all of the packages from one system to another without having to download them again. Though we advise against that, as manually moving the files means having to update the composer.json file yourself – needless to say, it could get messy. Just let Composer take care of the dependencies. Oh, and one more thing: those of you using Git or any other Version Control System (VCS) must not add the vendor folder to your repo.

Speaking of package versions, you can also see that the first line of the output of the above command states the version of phpunit/php-timer downloaded by Composer. In our case, it should read:

The Caret (^) sign is defined by Composer as the option for ‘maximum interoperability.’ This simply means that whenever the sign appears in front of a version, Composer will always allow updates to that package unless it breaks the package in some way. In our case, Composer will allow updates to the package within the range >=1.0.9 <2.0.0, as 2.0.0 will break backwards the compatibility. For a detailed read on versioning in Composer, hop on to the documentation page.

Step 3 – Using Autoload Script

If you’ve made it this far, the rest should be a cakewalk. Your dependencies have been installed, and your project is good to go. Well, almost.

You now need to load these dependencies into your PHP script. This would have been unnecessarily time-consuming if not for Composer’s autoload file. The file is located in the vendor directory of your project. Including this single file in your PHP script ensures that every package installed for the project is visible to the script.

To achieve autoloading, simply write the following line before you declare or instantiate any new variables in your script:

A sample script is given below to give you a better idea:

Run the script. Upon execution, it should display an output similar to the following:

Step 4 – Updating Your Project Dependencies

All that’s left is for you to know how to update your packages when needed. This can be done in one of two ways:

  • Universal Update
    To check for, and install updates for all of your packages and dependencies at once, type in the following command in the terminal:composer update
  • Package-specific Update
    Sometimes, you might want to check for updates related to particular packages. No problem, just execute your command in the format given below:composer update vendor/package vendor2/package2

Remember to replace vendor/package with the name of the package that you want to update.

By running the update command, Composer also updates the composer.json and composer.lock files to match the current state of your project dependencies.

Conclusion

Developers shouldn’t have to sort out dependency management on their own or develop their own solutions to problems that have already been solved a million times before by others. They should be able to pick-up existing open-source solutions and incorporate them in their projects with ease.

That is why Composer is such a handy weapon in one’s web development arsenal. You won’t have to waste any more precious man-hours on resolving dependencies. Instead, you’ll get to utilize that time and energy on other areas of your project.

Add Comment

Click here to post a comment

Com Domain Sale

Join thousands of subscribers worldwide

and get awesome deals & the newest tutorials to your email

Please wait...

Thank you for sign up!

More in PHP
How to Connect PHP to MySQL Database
How to Connect PHP to MySQL Database

Close