PHP Composer

Manish Kumar
2 min readJan 12, 2023

In this article, we will learn about what Composer is, how to install it, and how to use it to manage dependencies in our PHP projects.

What is Composer?
Composer is a dependency management tool for PHP. It allows developers to easily manage the external libraries and packages that their projects rely on. It does this by managing the dependencies and versions of those libraries, and automatically downloading and updating them as needed.

Installing Composer :
To install Composer, we first need to download the installer script. We can do this by running the following command:

php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"

Next, we need to verify that the installer script is not tampered with by running the following command:

php -r "if (hash_file('sha384', 'composer-setup.php') === '8a6138e2a05a8c28539c9f0fb361159823655d7ad2deecb371b04a83966c61223adc522b0189079e3e9e277cd72b8897') { 
echo 'Installer verified';
} else {
echo 'Installer corrupt'; unlink('composer-setup.php');
}
echo PHP_EOL;"

If the output is “Installer verified”, we can proceed to run the following command to install Composer globally:

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

Using Composer :
Once Composer is installed, we can use it to manage dependencies in our PHP projects. To do this, we first need to create a composer.json file in the root of our project. This file will contain information about the dependencies that our project needs.

For example, to add a dependency on the PHPUnit testing framework, we would add the following to our composer.json file:

{
"require": {
"phpunit/phpunit": "^8.5"
}
}

Then we can run the following command to install the dependencies specified in the composer.json file:

composer install

Updating Dependencies:
We can update our dependencies to their latest versions by running the following command:

composer update

Conclusion:
In this lesson, we have learned about PHP Composer and how to use it to manage dependencies in our PHP projects. We have seen how to install Composer, how to add dependencies to our project, and how to update those dependencies. By using Composer, we can easily manage the external libraries that our projects rely on and make sure that we are always using the latest and most stable versions of those libraries.

--

--