Composer

A Dependency Manager for PHP

Composer is an application-level package manager for the PHP programming language that provides a standard format for managing dependencies of PHP software and required libraries. It was developed by Nils Adermann and Jordi Boggiano in 2012, who continue to manage the project.


To install composer in windows download and install executable file
https://getcomposer.org/download/

To install in ubuntu

apt install composer

To install latest version of composer on ubuntu

cd ~
curl -sS https://getcomposer.org/installer -o composer-setup.php

sudo php composer-setup.php --install-dir=/usr/bin --filename=composer

OR

sudo php composer-setup.php --install-dir=/usr/local/bin --filename=composer

composer.json
Keep this file in the project’s root directory
NOTE: This file is mandatory to in root directory to use composer as composer look for this file when you run dump-autoload

{
	"autoload" : {
		"files" : ["lib/global_functions.php"],
	}
}

lib/global_functions.php

function getMessage() {
	
	echo "Hello World" . PHP_EOL;

}

Create autoload file by running any one following command

composer dump-autoload
composer dump-autoload -o

index.php

<?php
require("vendor/autoload.php");
echo "=====================\n";
getMessage();

How to autoload classes using composer

app/admin/Account.php

<?php
namespace App\Admin;

class Account {
	//this is magic method as it will invoked automatically 
        //when you create instance of account
	public function __construct() {
		
		echo "I am from Admin Account" . PHP_EOL;
	}
}

app/user/Account.php

<?php
namespace App\User;

class Account {
	//this is magic method as it will invoked automatically 
	//when you create instance of account
	public function __construct() {
		echo "I am from User Account" . PHP_EOL;
	}	
}

modify composer.json

{
	"autoload" : {
		"files" : ["lib/global_functions.php"],
		"classmap" : ["app"]
	}
}

Once you modify composer.json file run dump-autoload command again to add classmapping in autoload file

composer update

OR

composer dump-autoload -o

modify index.php

<?php

require("vendor/autoload.php");

echo "=====================\n";

getMessage();

echo "=====================\n";

new App\User\Account();

echo "=====================\n";

new App\Admin\Account();

echo "=====================\n";
directory structure

Ref Code: https://gitlab.com/codeinsightacademy/composer-demo.git

Leave a Reply

Your email address will not be published. Required fields are marked *