Good content takes time and effort to come up with.

Please consider supporting us by just disabling your AD BLOCKER and reloading this page again.







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


Share On     Share On WhatsApp     Share On LinkedIn


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 in simple terms Composer is a dependency manger which 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 composer does for you, it acts as your mother.


2) Why You Should Start Using Composer


Think that your working on 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 has security updates then you have to go download new version download it and change all its settings.


This goes for main Libraries/Packages too, if they have security updates or 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 super saver for your life. It manages all these stuffs 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 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 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 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 folder where your PHP runs. Mine is setup as shown in the following image


Composer Project Location

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 this packages are required for your project development & to download these packages when we install or update 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 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 you 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 couple of interactive question just fill them as shown in the below image


Installing via composer init command

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 above 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 composer require command this will create composer.json file if it does not exists 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 require option.


6) Working With Composer


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


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


This usually create vendor folder & composer.lock file along side 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 see the following folder vendor & new file composer.lock as shown in the following image


Project Folder Structure After composer install

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 folder. Make to add it in .gitignore if your 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 you in depth about composer install & composer update.


composer.lock - This is 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 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 composer.json file and updates 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: Lets 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 version was 1.9.0. When you do 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 use 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 exists then run composer-update and create it
  3. If exists then read composer.lock file for installation fo 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 composer.


composer.json - when using composer update command


composer.lock - when using composer install command


9) Difference between require & require-dev


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


require-dev - Packages inside this key will be only used to development & testing purpose. It wont 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 to 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 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 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 learnt what is composer how to install packages in composer. Now lets learn how to use it.


The following is how your project structure looks like.


Autoloading

Autoloading


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


Now this autoloading feature is built in with 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 your using 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 your 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.


WHATS NEXT?


You might be interested in reading few of my other articles


How To Install Packages Parallel For Faster Development In Composer

How To Implement REST API's With Examples (Coming Soon)

How To Secure Your REST API's? (Coming Soon)

Route Model Binding In Laravel & Change Default Column id To Another Column

How To Run Raw Queries Securely In Laravel

Laravel 7.x Multiple Database Connections, Migrations, Relationships & Querying

How To Install Apache Web Server On Ubuntu 20.04 / Linux & Manage It

How To Create / Save / Download PDF From Blade Template In PHP Laravel

How To Add Free SSL Certificate In cPanel With ZeroSSL & Certbot

How To Securely SSH Your Server & Push Files With FileZilla

How To Push Files To CPanel / Remote Server using FTP Software FileZilla

How To Install Linux, Apache, MYSQL, PHP (LAMP Stack) on Ubuntu

How To Cache Static Files With NGINX Server

Redirect www to a non-www website or vice versa

How To Create Free SSL Certificate With Lets Encrypt/Certbot In Linux (Single / Multiple Domains)

How To Install Linux, NGINX, MYSQL, PHP (LEMP Stack) on Ubuntu

PHP Built-In Web Server & Testing Your Development Project In Mobile Without Any Software

How To Do Google reCAPTCHA Integration In PHP Laravel Forms


Happy Coding :)








Author Image
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