DEV Community

keikesu0122
keikesu0122

Posted on

How does Composer help you manage php libraries?

1.What is Composer?
Composer helps you manage php libraries. Let's assume that you want to use library A that depends on library B. Without Composer, you would need to install library A and B by hand. Meanwhile, if you use Composer to install library A, you don't care about library B because Composer automatically installs libraries required by library A.

2.How to install Composer on Centos7

  • Add EPEL and REMI repositories
sudo yum install epel-release

sudo yum install https://rpms.remirepo.net/enterprise/remi-release-7.rpm
Enter fullscreen mode Exit fullscreen mode
  • Install Composer
sudo yum install --enablerepo=remi,remi-php73 php-pecl-zip composer
Enter fullscreen mode Exit fullscreen mode
  • Check the Composer version to confirm that Composer has been property installed
composer -v
Enter fullscreen mode Exit fullscreen mode

3.How to install libraries using Composer
There are two ways to install libraries with Composer.
Let's take the installation of monolog library as an example.

  • Use composer require Simply implement the following command to install monolog.
composer require monolog/monolog:"^2.0"
Enter fullscreen mode Exit fullscreen mode

The library information consists of vendor name/project name:version, which is recorded in composer.json. With the command above, you can use monolog.

  • Use composer install

Add the following code in composer.json.

"require": {
    "monolog/monolog": "^2.0"
}
Enter fullscreen mode Exit fullscreen mode

Implement the following command.

composer install
Enter fullscreen mode Exit fullscreen mode

composer install installs the libraries written in composer.json. Now, you can use monolog.

The installed libraries are stored in /vendor, and you need to add require("vendor/autoload.php"); to your php program in order to use the libraries.

4.What is the difference among composer require, composer install and composer update?
As mentioned earlier, composer require is used to install a new library, and the installed library is recorded in composer.json. composer install installs the libraries in composer.json, and their versions depend on the composer.lock, which manages library versions. For example, if you want to install the libraries you're currently using onto a different development environment, you should copy composer.json and composer.lock and execute composer install so that the same libraries will be installed there. composer update is used to update the versions of the libraries recorded in composer.json. Aforementioned, the version information is recorded in composer.lock.

Discussion (0)