- Introduction
- composer.json: Project setup
- The require key
- Package names
- Package version constraints
- Installing dependencies
- Commit your composer.lock file to version control
- Installing from composer.lock
- Updating dependencies to their latest versions
- Packagist
- Platform packages
- Autoloading
Introduction#
For our basic usage introduction, we will be installing monolog/monolog
,a logging library. If you have not yet installed Composer, refer to theIntro chapter.
Note: for the sake of simplicity, this introduction will assume youhave performed a local install of Composer.
composer.json
: Project setup#
To start using Composer in your project, all you need is a composer.json
file. This file describes the dependencies of your project and may containother metadata as well. It typically should go in the top-most directory ofyour project/VCS repository. You can technically run Composer anywhere butif you want to publish a package to Packagist.org, it will have to be ableto find the file at the top of your VCS repository.
The require
key#
The first thing you specify in composer.json
is therequire key. You are telling Composer whichpackages your project depends on.
{ "require": { "monolog/monolog": "2.0.*" }}
As you can see, require takes an object that mapspackage names (e.g. monolog/monolog
) to version constraints (e.g.1.0.*
).
Composer uses this information to search for the right set of files in package"repositories" that you register using the repositorieskey, or in Packagist.org, the default package repository.In the above example, since no other repository has been registered in thecomposer.json
file, it is assumed that the monolog/monolog
package is registeredon Packagist.org. (Read more about Packagist, andabout repositories).
Package names#
The package name consists of a vendor name and the project's name. Often thesewill be identical - the vendor name only exists to prevent naming clashes. Forexample, it would allow two different people to create a library named json
.One might be named igorw/json
while the other might be seldaek/json
.
Read more about publishing packages and package naming.(Note that you can also specify "platform packages" as dependencies, allowingyou to require certain versions of server software. Seeplatform packages below.)
Package version constraints#
In our example, we are requesting the Monolog package with the version constraint2.0.*
.This means any version in the 2.0
development branch, or any version that isgreater than or equal to 2.0 and less than 2.1 (>=2.0 <2.1
).
Please read versions for more in-depth information onversions, how versions relate to each other, and on version constraints.
How does Composer download the right files? When you specify a dependency in
composer.json
, Composer first takes the name of the package that you have requestedand searches for it in any repositories that you have registered using therepositories key. If you have not registeredany extra repositories, or it does not find a package with that name in therepositories you have specified, it falls back to Packagist.org (more below).When Composer finds the right package, either in Packagist.org or in a repo you have specified,it then uses the versioning features of the package's VCS (i.e., branches and tags)to attempt to find the best match for the version constraint you have specified. Be sure to readabout versions and package resolution in the versions article.
Note: If you are trying to require a package but Composer throws an errorregarding package stability, the version you have specified may not meet yourdefault minimum stability requirements. By default, only stable releases are takeninto consideration when searching for valid package versions in your VCS.
You might run into this if you are trying to require dev, alpha, beta, or RCversions of a package. Read more about stability flags and the
minimum-stability
key on the schema page.
Installing dependencies#
To initially install the defined dependencies for your project, you should run theupdate command.
php composer.phar update
This will make Composer do two things:
- It resolves all dependencies listed in your
composer.json
file and writes all of thepackages and their exact versions to thecomposer.lock
file, locking the project tothose specific versions. You should commit thecomposer.lock
file to your project reposo that all people working on the project are locked to the same versions of dependencies(more below). This is the main role of theupdate
command. - It then implicitly runs the install command. This will downloadthe dependencies' files into the
vendor
directory in your project. (Thevendor
directory is the conventional location for all third-party code in a project). In ourexample from above, you would end up with the Monolog source files invendor/monolog/monolog/
. As Monolog has a dependency onpsr/log
, that package's filescan also be found insidevendor/
.
Tip: If you are using git for your project, you probably want to add
vendor
in your.gitignore
. You really don't want to add all of thatthird-party code to your versioned repository.
Commit your composer.lock
file to version control#
Committing this file to version control is important because it will cause anyonewho sets up the project to use the exact sameversions of the dependencies that you are using. Your CI server, productionmachines, other developers in your team, everything and everyone runs on thesame dependencies, which mitigates the potential for bugs affecting only someparts of the deployments. Even if you develop alone, in six months whenreinstalling the project you can feel confident that the dependencies installed arestill working, even if the dependencies have released many new versions since then.(See note below about using the update
command.)
Note: For libraries it is not necessary to commit the lockfile, see also: Libraries - Lock file.
Installing from composer.lock
#
If there is already a composer.lock
file in the project folder, it means eitheryou ran the update
command before, or someone else on the project ran the update
command and committed the composer.lock
file to the project (which is good).
Either way, running install
when a composer.lock
file is present resolves and installsall dependencies that you listed in composer.json
, but Composer uses the exact versions listedin composer.lock
to ensure that the package versions are consistent for everyoneworking on your project. As a result you will have all dependencies requested by yourcomposer.json
file, but they may not all be at the very latest available versions(some of the dependencies listed in the composer.lock
file may have released newer versions sincethe file was created). This is by design, ensuring that your project does not break because ofunexpected changes in dependencies.
So after fetching new changes from your VCS repository it is recommended to runa Composer install
to make sure the vendor directory is up in sync with yourcomposer.lock
file.
php composer.phar install
Composer enables reproducible builds by default. This means that running thesame command multiple times will produce a vendor/
directory containing filesthat are identical (except their timestamps), including the autoloader files.It is especially beneficial for environments that require strictverification processes, as well as for Linux distributions aiming to package PHPapplications in a secure and predictable manner.
Updating dependencies to their latest versions#
As mentioned above, the composer.lock
file prevents you from automatically gettingthe latest versions of your dependencies. To update to the latest versions, use theupdate command. This will fetch the latest matchingversions (according to your composer.json
file) and update the lock filewith the new versions.
php composer.phar update
Note: Composer will display a Warning when executing an
install
commandif thecomposer.lock
has not been updated since changes were made to thecomposer.json
that might affect dependency resolution.
If you only want to install, upgrade or remove one dependency, you can explicitly list it as an argument:
php composer.phar update monolog/monolog [...]
Packagist#
Packagist.org is the main Composer repository. A Composerrepository is basically a package source: a place where you can get packagesfrom. Packagist aims to be the central repository that everybody uses. Thismeans that you can automatically require
any package that is available there,without further specifying where Composer should look for the package.
If you go to the Packagist.org website,you can browse and search for packages.
Any open source project using Composer is recommended to publish their packageson Packagist. A library does not need to be on Packagist to be used by Composer,but it enables discovery and adoption by other developers more quickly.
Platform packages#
Composer has platform packages, which are virtual packages for things that areinstalled on the system but are not actually installable by Composer. Thisincludes PHP itself, PHP extensions and some system libraries.
php
represents the PHP version of the user, allowing you to applyconstraints, e.g.^7.1
. To require a 64bit version of php, you canrequire thephp-64bit
package.hhvm
represents the version of the HHVM runtime and allows you to applya constraint, e.g.,^2.3
.ext-<name>
allows you to require PHP extensions (includes coreextensions). Versioning can be quite inconsistent here, so it's oftena good idea to set the constraint to*
. An example of an extensionpackage name isext-gd
.lib-<name>
allows constraints to be made on versions of libraries used byPHP. The following are available:curl
,iconv
,icu
,libxml
,openssl
,pcre
,uuid
,xsl
.
You can use show --platform to get a list of your locallyavailable platform packages.
Autoloading#
For libraries that specify autoload information, Composer generates avendor/autoload.php
file. You can include this file and startusing the classes that those libraries provide without any extra work:
require __DIR__ . '/vendor/autoload.php';$log = new Monolog\Logger('name');$log->pushHandler(new Monolog\Handler\StreamHandler('app.log', Monolog\Logger::WARNING));$log->warning('Foo');
You can even add your own code to the autoloader by adding anautoload field to composer.json
.
{ "autoload": { "psr-4": {"Acme\\": "src/"} }}
Composer will register a PSR-4 autoloaderfor the Acme
namespace.
You define a mapping from namespaces to directories. The src
directory wouldbe in your project root, on the same level as the vendor
directory. An examplefilename would be src/Foo.php
containing an Acme\Foo
class.
After adding the autoload field, you have to re-runthis command:
php composer.phar dump-autoload
This command will re-generate the vendor/autoload.php
file.See the dump-autoload section formore information.
Including that file will also return the autoloader instance, so you can storethe return value of the include call in a variable and add more namespaces.This can be useful for autoloading classes in a test suite, for example.
$loader = require __DIR__ . '/vendor/autoload.php';$loader->addPsr4('Acme\\Test\\', __DIR__);
In addition to PSR-4 autoloading, Composer also supports PSR-0, classmap andfiles autoloading. See the autoload reference formore information.
See also the docs on optimizing the autoloader.
Note: Composer provides its own autoloader. If you don't want to use thatone, you can include
vendor/composer/autoload_*.php
files, which returnassociative arrays allowing you to configure your own autoloader.
← Intro | Libraries →
Found a typo? Something is wrong in this documentation? Fork and edit it!