Gareth Redfern developer, cyclist & coffee lover

Basic Composer Usage In PHP

Posted by Gareth Redfern
Category: php Tags: composer

To get started using Composer you will first need to install it globally, to do this open up your terminal and type:

curl -sS | php

Once installed you will then likely want to add a shortcut so that you can type composer to make use of it’s commands. Type the following into your terminal:

mv composer.phar /usr/local/bin/composer

Now you can easily access composer globally with one command: composer.

Once installed you will the be able to search for packages that are available on Packagist and Composer will manage the dependencies. For Composer to work it needs to have a composer.json file, which provides information about your project and lists any required packages you want to use. To have Composer create your json file open up your terminal and navigate to your project’s route directory. Type composer init and Composer will run through a series of questions to get your project started. To keep things simple hit enter to say yes to each of the questions. You should end up with a composer.json file that looks like the following:

  "name": "root/projectfolder",
  "authors": [
      "name": "Gareth Redfern",
      "email": ""
  "require": {}

The above composer.json file doesn’t do much at the moment because it isn’t requiring any packages, but it does provide the skeleton information for your project. To search and add a package type the following into your terminal (assuming you are still in the project route)

composer require

The prompt will ask you to search for a package. In this example lets search for the Monolog package by typing monolog into the terminal. The first package result which comes up is monolog/monolog type 0 to select it then hit enter to answer yes to each of the questions. Finally hit enter and Composer will install Monolog and all its dependencies for you in a new folder called vendor. You will also see that Composer updated the required object in the composer.json file to include monolog/monolog and it created a composer.lock file for handling the projects version of Monolog that will be used.

You have now set everything up so that you can manage all your dependencies and packages using Composer, the next step is to learn how to use the monolog package using autoloading with the autoload.php file created in your vendor folder.