What Is Composer? How Does It Work? Useful Composer Commands And Usage


Share On        


In this article, you will learn

  1. What Is Composer
  2. Why You Should Start Using Composer
  3. Installation In Ubuntu/Windows/Mac
  4. Check If Composer Is Installed Properly
  5. composer.json File Creation
  6. Working With Composer (Will Explain Vendor folder & composer.lock file)
  7. composer update v/s composer install
  8. What Is composer.json & composer.lock?
  9. Difference Between require & require-dev
  10. Remove Installed Packages
  11. Useful Commands In Your Daily Life
  12. Autoloading Files With Composer With Faker Example

Sounds the topics are interesting right? Let's get started then


1) What Is Composer


To put it in simple terms Composer is a dependency manager that will manage all your project dependencies with ease.


Let me give you an example. When you want to eat something you will just ask your mother for it and she cooks for you. On the other hand you don't need to know whether the groceries is available or not, whether all the dishes are cleaned or not, where LPG gas cylinder is there or not. All this is managed by your mother ( Even if not then just pretend for the sake of example :) ).


The same way the composer does for you, it acts like your mother. It installs, updates, and manages all your project dependencies.


2) Why You Should Start Using Composer


Think that you are working on a big project and you have requirements of Excel-Sheet, PDF, Zip & UnZip, Email Libraries/Packages. You usually download these Libraries/Packages and keep in some libraries folder of your project.


If these Libraries/Packages, in turn, depend on 3 other Libraries/Packages and when these dependable packages have security updates then you have to go download a new version download it, and change all its settings.


This goes for main Libraries/Packages too, if they have security updates or a newer version then you should download it and do all the settings manually as you did earlier.

Oh! God what the heck!


COMPOSER comes as a super saver for your life. It manages all this stuff for you and you can work peacefully.


Okay! What about the outdated packages? Yes with composer commands you can find that too and upgrade them with ease.


3) Installation In Ubuntu/Windows/Mac


Ubuntu Installation


sudo apt-get update
sudo apt-get install composer

Windows Installation


Download by clicking this link -> GetComposer & follow the standard installation process.


MacBook Installation


By using HomeBrew. If your still not using HomeBrew then I highly suggest you to use it. Your life will be lot easier with it.


brew install composer

4) Check If Composer Is Installed Properly


Check if the composer is installed properly or not using the following command


composer -v


You must get similar to the following output


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

Usage:
 command [options] [arguments]

Options:
 -h, --help           Display this help message
 -q, --quiet          Do not output any message
 -V, --version         Display this application version
   --ansi           Force ANSI output
   --no-ansi         Disable ANSI output
 -n, --no-interaction      Do not ask any interactive question
   --profile         Display timing and memory usage information
   --no-plugins        Whether to disable plugins.
 -d, --working-dir=WORKING-DIR If specified, use the given directory as working directory.
   --no-cache         Prevent use of the cache
 -v|vv|vvv, --verbose      Increase the verbosity of messages: 1 for normal output, 2 for more verb


If you have any issues then do let me know in the comments I will help you out.


5) composer.json File Creation


I am using composer-training folder for the sake of demonstration, usually you create in htdocs or /var/www/html the folder where your PHP runs. Mine is set up as shown in the following image


Composer Project Location


composer gets to know what packages to download for your project based on composer.json file.

composer.json can be created with any of the following 3 ways

i. Manual composer.json file creation

ii. With composer ini command

iii. With composer require command


The bare minimum syntax for your composer is as follows:


{
    "require": {
        "fzaninotto/faker": "^1.9"
    }
}


require - Tells composer that these packages are required for your project development & to download these packages when we install or update the composer.json file


fzaninotto/faker is the name of the package you want to install for your project. Faker package is used to generate fake data. I have written a whole article on it @ How To Generate Fake Data In PHP With Faker.


i. Manual composer.json creation


As shown in the above syntax just go for your project folder ie composer-training as of now and create composer.json file and add the following code


{
    "require": {
        "fzaninotto/faker": "^1.9"
    }
}


After creating the composer.json like the above way you need to go for terminal and run the following command to install


composer install

ii. With composer init command


You can go for the project folder and run the following command for an interactive way of generating the composer.json file.


composer init


This will ask for a couple of interactive questions just fill them as shown in the below image


Installing via composer init command


You can specify dependencies & development dependencies while creating the composer.json file. But here I have ignored it. Don't worry about these terms I will explain them soon.


This will generate the composer.json file as follows


{
    "name": "wifidabba/composer-training",
    "description": "Composer training",
    "authors": [
        {
            "name": "Channaveer Hakari",
            "email": "channaveer@wifidabba.com"
        }
    ],
    "require": {}
}


Add Faker package in the composer.json file as follows


"require": {
    "fzaninotto/faker": "^1.9"
}


After creating the composer.json like the above way you need to go for terminal and run the following command to install


composer install

iii. With composer require Command


You can directly run the composer require command this will create a composer.json file if it does not exist and if already exists then it will add-in require or require-dev keys value.


composer require fzaninotto/faker


You can use any of the above 3 ways, but my best one is iii. composer requires an option.


6) Working With Composer


Now composer.json file is created and packages have been added now what.


When you run the composer install command composer will go and read the composer.json file and install the packages from require & require-dev.


This usually creates vendor folder & composer.lock file alongside with you composer.json file and other project files


composer install


Updating dependencies (including require-dev)
Package operations: 1 install, 0 updates, 0 removals
 - Installing fzaninotto/faker (v1.9.1): Loading from cache
Writing lock file
Generating autoload files



VENDOR Folder & composer.lock File


Now when you go to your project folder you will be able to see the following folder vendor & new file composer.lock as shown in the following image


Project Folder Structure After composer install


vendor - All your libraries required for the project and that you have added in require or require-dev will be in this folder.

Don't commit this folder as this will have too many files and folders. Make to add it in .gitignore if you are using GIT. If any of your teammates need to install all these files then let him use composer install command. In the upcoming sections, I will explain to you in-depth about composer install & composer update.


composer.lock - This is a very important file when you use version control make sure to commit this file too. I will explain the difference between composer.lock & composer.json file in the next section. But before proceeding with compose.lock & composer.json you need to understand the difference between composer install & composer update


7) composer update v/s composer install


Composer Update (Strictly use only during development)


When you do composer update it will check for the composer.json file and update all the packages/libraries that are listed in it & once the packages are updated it will rewrite new updates in composer.json & composer.lock file by deleting old package updates.


Basically the following process


  1. Read composer.json
  2. Remove installed packages that are not required in composer.json
  3. Check latest versions of required packages in composer.json from https://packagist.org
  4. Install the latest versions of your packages
  5. Update composer.lock with installed packages version & even update composer.json file with it
  6. composer install


Eg: Let's take an example of this, in your composer.json file you may have this


"require": {
    "fzaninotto/faker": "^1.9"
}


You have installed faker 4 months back in your project with a version was 1.9.0. When you do a composer update composer will go and check in its repositories if any new update available for the package. If any new update like 1.9.5 then it will go ahead and update the package to 1.9.5.


Composer Install (Can used during development & production environment)


When you do composer install it will check for composer.lock file and install all the packages/libraries that are listed in composer.lock file.


This command won't update anything like composer update.


  1. composer.lock file 
  2. If it does not exist then run composer-update and create it
  3. If exists then read composer.lock file for installation of packages
  4. Install the packages specified in the composer.lock file

8) composer.json & composer.lock


Based on the above composer install & composer update section you would now have a clear understanding of when composer.json & when composer.lock files are used by the composer.


composer.json - when using the composer update command


composer.lock - when using the composer install command


9) Difference between require & require-dev


require - Packages inside this key will be used for production purposes.


require-dev - Packages inside this key will be only used for development & testing purposes. It won't be used in the production project.


NOTE: I have used Faker package in require purely for the sake of demonstration. Don't used it in required unless and until you use for production ready project


Example: PHPUnit - PHPUnit is like jUnit which is used for PHPUnit testing.


In command line

composer require --dev phpunit/phpunit


OR


In composer.json file directly

"require-dev": {
    "phpunit/phpunit": "^4.8.35 || ^5.7",
},

10) Remove Composer Installed Packages


To remove any installed from require or require-dev packages just use the following command.


composer remove package_name


Example:


composer remove fzaninotto/faker


11) Composer Commands For Your Daily Work


composer -V (Capital V)-> Show composer version


composer -v (Small v) -> Show composer version with verbose output ie with all help commands


composer -> same as composer -v


composer -h -> Composer available commands for usage


composer install / composer i -> Installs the project dependencies from the composer.lock file if present, or falls back on the composer.json


composer update / composer u -> Upgrades your dependencies to the latest version according to composer.json, and updates the composer.lock file.


composer init -> Creates a basic composer.json file in the current directory


composer clear-cache / composer clearcache - Clear composer internal package cache


composer require -> Install & adds composer package to composer.json

Example: composer require guzzlehttp/guzzle

composer require --dev phpunit/phpunit


composer info -> Shows information about packages


composer dumpautoload / composer dump-autoload -> dumps the autoloader and rebuilds the files


composer global -> Install packages in the global composer directory which can be used from anywhere

Example: composer global require phpunit/phpunit


composer search -> Search the packages from the remote package repository.


12) Autoloading Files With Composer With Faker Example


Now you learned what is composer how to install packages in composer. Now let's learn how to use it.


The following is how your project structure looks like.


Autoloading


Before autoloading existed you manually used to require or include all the classes or the files that you used to use.


Now, this autoloading feature is built-in with the composer's vendor folder. There is a file called autoload.php file which will autoload all the packages/libraries files inside this vendor folder.


So if you using the plan PHP framework then you have to include this autoload.php file in your file on the first line as shown in the above image


<?php
/** Include autoload.php for autoloading the classes used in Faker */
require_once './vendor/autoload.php';


If you using frameworks then automatically it will include this autoload.php file in its boot-loader and will be called automatically when you call any file.


Following is the simple implementation of the same


<?php
/** Include autoload.php for autoloading the classes used in Faker */
require_once './vendor/autoload.php';

/** Faker Factory Object */
$faker = Faker\Factory::create('en_IN');

for($i = 0; $i <= 50; $i++){
  echo $faker->name."<br>";
  /** You can use DB Connection To Store Data */
}

Conclusion


Hope you really liked this article. If yes, then please share with your friends.




AUTHOR

Channaveer Hakari

I am a full-stack developer working at WifiDabba India Pvt Ltd. I started this blog so that I can share my knowledge and enhance my skills with constant learning.

Never stop learning. If you stop learning, you stop growing