How to Install and Use Composer – The Complete Tutorial
access_time
hourglass_empty
person_outline

How to Install and Use Composer – The Complete Tutorial

In this article, we are going to show you how to install and use Composer on various platforms. To help you master this tool, you will also learn how to create a basic PHP project.

Introduction to Composer

Composer is a dependency manager for PHP. It is a simple and reliable tool that developers use to manage and integrate external packages into their PHP-based projects. This way, they don’t have to build their webpages or web applications from the ground-up.

What’s great, Composer can resolve dependencies on a per-project basis. Thus, developers can control packages for each project and keep the project size in check.

Before you learn how to install Composer, make sure that you have access to the command line interface on your system or server.

Cyber sale for up to 90% OFF. Install and use Composer with powerful web hosting solutions!

90% OFF for Web Hosting

Step 1: Installing Composer

This section will show you how to install Composer on shared hosting and popular operating systems like Linux, macOS, and Windows.

1. Installing Composer on Shared Hosting, Linux, or macOS

The commands to install Composer on shared hosting, Linux (PC or server), and macOS are the same.

Note that Composer comes pre-installed on Hostinger’s Premium and Business shared hosting plans. If you are using one of them, skip this part. However, if you find out that it’s outdated, you can update Composer by running this command:

php composer.phar self-update

Follow this instruction to know how to install Composer on your system:

  1. Connect to your hosting account using SSH connection. You can learn how to do so from our SSH tutorial.
  2. Download Composer from the official website using the following command:
    php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
  3. Verify the installer’s signature (SHA-384) to ensure that the installer file is not corrupt. Enter:
    php -r "if (hash_file('sha384', 'composer-setup.php') === 'a5c698ffe4b8e849a443b120cd5ba38043260d5c4023dbf93e1558871f1f07f58274fc6f4c93bcfd858c6bd0775cd8d1') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"

    The long string of characters in the above command (‘a5c698ff…’) is the installer’s signature. It changes every time a new version of Composer comes out. Therefore, be sure to fetch the latest SHA-384 from this page.

  4. Once it’s done, you may install Composer locally or globally. Local installation means that the dependency manager will be stored in your current directory, and you have to specify the path before executing corresponding commands. Meanwhile, global installation allows you to run Composer from anywhere on your system by storing it in /usr/local/bin directory.Here is how to complete both methods:
    • Local installation:
      php composer-setup.php
    • Global installation:
      php composer-setup.php --install-dir=/usr/local/bin --filename=composer

      You will get this result:

      All settings correct for using Composer
      Downloading...
      
      Composer (version 1.9.1) successfully installed to: /usr/local/bin/composer
  5. Once it’s done, remove the installer:
    php -r "unlink('composer-setup.php');"
  6. Test the Composer installation:
    composer

    The command line will return with this result:

       ______
      / ____/___ ____ ___ ____ ____ ________ _____
     / / / __ / __ `__ / __ / __ / ___/ _ / ___/
    / /___/ /_/ / / / / / / /_/ / /_/ (__ ) __/ /
    ____/____/_/ /_/ /_/ .___/____/____/___/_/
                      /_/
    
    Composer version 1.9.1 2019-11-15 16:20:11

2. Installing Composer on Windows

Like most other programs, getting started with Composer is much simpler on a Windows machine. No command line instruction is necessary for downloading and installing the software.

Simply follow these steps:

  1. Install PHP on your computer. We recommend using XAMPP for this purpose, as the process is straightforward and you can complete it in a few minutes.
  2. Once XAMPP is installed, download the latest version of Composer.
  3. Run Composer installation wizard. When it asks you to activate the developer mode, ignore it and continue with the installation process.Composer installation wizard on Windows
  4. Another window will pop up and ask you to locate the PHP command line. By default, it is in C:/xampp/php/php.exe. After specifying the location, click Next.
  5. You will be prompted with Proxy Settings. Don’t check the box and skip this part by hitting Next. Then, on the last window, click Install.
  6. After completing the installation, open the command prompt. Press CTRL +R, type in “cmd,” and click OK.
    The Run application to open command prompt on Windows
  7. Enter the following command:
    composer

Great job! You have installed Composer on your Windows computer. The installer will automatically add Composer to your PATH variable. Now you can open the command prompt and run the software from anywhere.

Step 2: Generating and Understanding composer.json

Now comes the interesting part — using Composer in your PHP project.

To achieve this, you need to generate a composer.json file. You can think of it as a lookup list for Composer. This file contains packages (dependencies) that should be downloaded.

Furthermore, composer.json also checks for version compatibility with your project. This means if you are using an older package, composer.json will let you know in order to avoid future issues.

You have the option to create and update composer.json yourself. However, considering that this is a tutorial on automating redundant tasks, we don’t recommend 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, which allows developers to find out how much time code takes to execute. This is highly useful for debugging and optimization purposes.

You can follow these steps:

  1. Create a new directory for the project. Since our project is a timer, we’ll simply name the folder phptimer. To do this, execute the following command:
    mkdir phptimer
  2. Enter the newly created directory:
    cd phptimer
  3. Find a package or library for the project. The best place to achieve that is Packagist, where you’ll find tons of libraries to help your project development. For this tutorial, we need a timer package. To get it, simply type ‘timer’ in the search bar:The interface of Packagist website where you can download dependency for Composer
    As you can see, several timer packages are available. Each has a name and a small description of what it does. In this example, we choose phpunit/php-timer as it has the most downloads and most GitHub stars.
  4. Specify the desired package so Composer can add it to your project:
    composer require phpunit/php-timer

    The output will show the version of phpunit/php-timer:

    Using version ^1.0 phpunit/php-timer

The caret (^) symbol is defined as the option for maximum interoperability. This means Composer will always update the package until a certain version breaks the package in some way.

In our case, the package update range is >=1.0.9 <2.0.0, as version 2.0.0 will break the backward compatibility. For detailed information about versioning in Composer, visit the documentation page.

After executing the above command, your project directory will have two new files — composer.json and composer.lock — and a folder named vendor. This is the directory where Composer will store all of your packages and dependencies.

Step 3: Using Autoload Script

Your project is almost good to go, and the only thing left to do is load the dependency into your PHP script. And fortunately, Composer’s autoload file helps you to complete this process faster.

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

require '/vendor/autoload.php'

We’ll give you an example to help you understand better.

Let’s say we want to test our phptimer project:

  1. Open nano text editor to create a script named demo.php.
    nano demo.php

    Then, paste the following lines to your file:

    <?php
    require __DIR__ . '/vendor/autoload.php'
    
    Timer::start();
    
    // your code
    
    $time = Timer::stop();
    
    var_dump($time);
    
    print Timer::secondsToTimeString($time);
  2. Run the script:
    php demo.php

    The terminal should display an output similar to the following:

    double(1.0893424438611E-5)
    0 ms

Step 4: Updating Your Project Dependencies

Lastly, you have to know how to update your packages. This can be done in one of two ways:

  • Universal update. To check and install updates for all of your packages and dependencies at once, type in the following command:
    composer update
  • Package-specific update. Execute this command to check the updates for one or more specific packages:
    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

Composer helps developers in managing dependencies of PHP projects. Thanks to this software, they can easily integrate and manage open source packages in a single place.

In this article, you have learned how to install and use Composer effectively. To summarize, let’s review all the steps once again:

  1. Installing Composer on shared hosting, Linux, macOS, or Windows system.
  2. Generating and understanding composer.json file.
  3. Using Autoload script to load dependencies into your PHP file.
  4. Updating your project dependencies.

We hope that by following our guide, you have a strong foundation to create amazing projects with PHP. Good luck and feel free to ask any questions in the comment section below!

The Author

Author

Domantas G. / @domantas

Domantas leads the content and SEO teams forward with fresh ideas and out of the box approaches. Armed with extensive SEO and marketing knowledge, he aims to spread the word of Hostinger to every corner of the world. During his free time, Domantas likes to hone his web development skills and travel to exotic places.

Related tutorials

Author

Narendra Reply

January 12, 2018

Thanks for this. It was straight forward and very easy to follow. I really appreciate the help.

Author

Nour Mait Reply

November 04, 2018

Danke schön . Ich habe viel gelesen , aber deine Artikel ist am besten . Danke wieder

    Author

    Gediminas B.

    Replied on November 06, 2018

    Hello, Nour. I'm glad to hear you found the article helpful. Viel Glück!

Author

Oduor sheban Reply

August 15, 2019

thanks bro

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Become a part of Hostinger now!

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

Close