PHP What is Composer?


Composer is a dependency/package manager for PHP. It can be used to install, keep track of, and update your project dependencies. Composer also takes care of autoloading the dependencies that your application relies on, letting you easily use the dependency inside your project without worrying about including them at the top of any given file.

Dependencies for your project are listed within a composer.json file which is typically located in your project root. This file holds information about the required versions of packages for production and also development.

A full outline of the composer.json schema can be found on the Composer Website.

This file can be edited manually using any text-editor or automatically through the command line via commands such as composer require <package> or composer require-dev <package>.

To start using composer in your project, you will need to create the composer.json file. You can either create it manually or simply run composer init. After you run composer init in your terminal, it will ask you for some basic information about your project: Package name (vendor/package - e.g. laravel/laravel), Description - optional, Author and some other information like Minimum Stability, License and Required Packages.

The require key in your composer.json file specifies Composer which packages your project depends on. require takes an object that maps package names (e.g. monolog/monolog) to version constraints (e.g. 1.0.*).

    "require": {
        "composer/composer": "1.2.*"

To install the defined dependencies, you will need to run the composer install command and it will then find the defined packages that matches the supplied version constraint and download it into the vendor directory. It's a convention to put third party code into a directory named vendor.

You will notice the install command also created a composer.lock file.

A composer.lock file is automatically generated by Composer. This file is used to track the currently installed versions and state of your dependencies. Running composer install will install packages to exactly the state stored in the lock file.