Source: https://getcomposer.org/doc/00-intro.md # Introduction Composer is a tool for dependency management in PHP. It allows you to declare the libraries your project depends on and it will manage (install/update) them for you. ## Dependency management Composer is **not** a package manager in the same sense as Yum or Apt are. Yes, it deals with "packages" or libraries, but it manages them on a per-project basis, installing them in a directory (e.g. `vendor`) inside your project. By default, it does not install anything globally. Thus, it is a dependency manager. It does however support a "global" project for convenience via the [global](https://getcomposer.org/doc/03-cli.md.md#global) command. This idea is not new and Composer is strongly inspired by node's [npm](https://www.npmjs.com/) and ruby's [bundler](https://bundler.io/). Suppose: 1. You have a project that depends on a number of libraries. 2. Some of those libraries depend on other libraries. Composer: 1. Enables you to declare the libraries you depend on. 2. Finds out which versions of which packages can and need to be installed, and installs them (meaning it downloads them into your project). 3. You can update all your dependencies in one command. See the [Basic usage](https://getcomposer.org/doc/01-basic-usage.md.md) chapter for more details on declaring dependencies. ## System Requirements Composer in its latest version requires PHP 7.2.5 to run. A long-term-support version (2.2.x) still offers support for PHP 5.3.2+ in case you are stuck with a legacy PHP version. A few sensitive php settings and compile flags are also required, but when using the installer you will be warned about any incompatibilities. Composer needs several supporting applications to work effectively, making the process of handling package dependencies more efficient. For decompressing files, Composer relies on tools like `7z` (or `7zz`), `gzip`, `tar`, `unrar`, `unzip` and `xz`. As for version control systems, Composer integrates seamlessly with Fossil, Git, Mercurial, Perforce and Subversion, thereby ensuring the application's smooth operation and management of library repositories. Before using Composer, ensure that these dependencies are correctly installed on your system. Composer is multi-platform and we strive to make it run equally well on Windows, Linux and macOS. ## Installation - Linux / Unix / macOS ### Downloading the Composer Executable Composer offers a convenient installer that you can execute directly from the command line. Feel free to [download this file](https://getcomposer.org/installer) or review it on [GitHub](https://github.com/composer/getcomposer.org/blob/main/web/installer) if you wish to know more about the inner workings of the installer. The source is plain PHP. There are, in short, two ways to install Composer. Locally as part of your project, or globally as a system wide executable. #### Locally To install Composer locally, run the installer in your project directory. See [the Download page](https://getcomposer.org/download/) for instructions. The installer will check a few PHP settings and then download `composer.phar` to your working directory. This file is the Composer binary. It is a PHAR (PHP archive), which is an archive format for PHP which can be run on the command line, amongst other things. Now run `php composer.phar` in order to run Composer. You can install Composer to a specific directory by using the `--install-dir` option and additionally (re)name it as well using the `--filename` option. When running the installer when following [the Download page instructions](https://getcomposer.org/download/) add the following parameters: ```shell php composer-setup.php --install-dir=bin --filename=composer ``` Now run `php bin/composer` in order to run Composer. #### Globally You can place the Composer PHAR anywhere you wish. If you put it in a directory that is part of your `PATH`, you can access it globally. On Unix systems you can even make it executable and invoke it without directly using the `php` interpreter. After running the installer following [the Download page instructions](https://getcomposer.org/download/) you can run this to move composer.phar to a directory that is in your path: ```shell mv composer.phar /usr/local/bin/composer ``` If you like to install it only for your user and avoid requiring root permissions, you can use `~/.local/bin` instead which is available by default on some Linux distributions. > **Note:** If the above fails due to permissions, you may need to run it again > with `sudo`. > **Note:** On some versions of macOS the `/usr` directory does not exist by > default. If you receive the error "/usr/local/bin/composer: No such file or > directory" then you must create the directory manually before proceeding: > `mkdir -p /usr/local/bin`. > **Note:** For information on changing your PATH, please read the > [Wikipedia article](https://en.wikipedia.org/wiki/PATH_(variable)) and/or use > your search engine of choice. Now run `composer` in order to run Composer instead of `php composer.phar`. ## Installation - Windows ### Using the Installer This is the easiest way to get Composer set up on your machine. Download and run [Composer-Setup.exe](https://getcomposer.org/Composer-Setup.exe). It will install the latest Composer version and set up your PATH so that you can call `composer` from any directory in your command line. > **Note:** Close your current terminal. Test usage with a new terminal: This is > important since the PATH only gets loaded when the terminal starts. ### Manual Installation Change to a directory on your `PATH` and run the installer following [the Download page instructions](https://getcomposer.org/download/) to download `composer.phar`. Create a new `composer.bat` file alongside `composer.phar`: Using cmd.exe: ```shell C:\bin> echo @php "%~dp0composer.phar" %*>composer.bat ``` Using PowerShell: ```shell PS C:\bin> Set-Content composer.bat '@php "%~dp0composer.phar" %*' ``` Add the directory to your PATH environment variable if it isn't already. For information on changing your PATH variable, please see [this article](https://www.computerhope.com/issues/ch000549.htm) and/or use your search engine of choice. Close your current terminal. Test usage with a new terminal: ```shell C:\Users\username>composer -V ``` ```text Composer version 2.4.0 2022-08-16 16:10:48 ``` ## Docker Image Composer is published as Docker container in a few places, see the list in the [composer/docker README](https://github.com/composer/docker). Example usage: ```shell docker pull composer/composer docker run --rm -it -v "$(pwd):/app" composer/composer install ``` To add Composer to an existing **Dockerfile** you can simply copy binary file from pre-built, low-size images: ```Dockerfile # Latest release COPY --from=composer/composer:latest-bin /composer /usr/bin/composer # Specific release COPY --from=composer/composer:2-bin /composer /usr/bin/composer ``` **Note:** you need to manually install other runtime dependencies inside your image when using this method; see also https://github.com/composer/composer/blob/main/README.md#binary-dependencies. Read the [image description](https://hub.docker.com/r/composer/composer) for further usage information. **Note:** Docker specific issues should be filed [on the composer/docker repository](https://github.com/composer/docker/issues). **Note:** You may also use `composer` instead of `composer/composer` as image name above. It is shorter and is a Docker official image but is not published directly by us and thus usually receives new releases with a delay of a few days. **Important**: short-aliased images don't have binary-only equivalents, so for `COPY --from` approach it's better to use `composer/composer` ones. ## Using Composer Now that you've installed Composer, you are ready to use it! Head on over to the next chapter for a short demonstration. [Basic usage](https://getcomposer.org/doc/01-basic-usage.md.md) → --- Source: https://getcomposer.org/doc/01-basic-usage.md # Basic usage ## Introduction For our basic usage introduction, we will be installing `monolog/monolog`, a logging library. If you have not yet installed Composer, refer to the [Intro](https://getcomposer.org/doc/00-intro.md.md) chapter. > **Note:** for the sake of simplicity, this introduction will assume you > have performed a [local](https://getcomposer.org/doc/00-intro.md.md#locally) 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 contain other metadata as well. It typically should go in the top-most directory of your project/VCS repository. You can technically run Composer anywhere but if you want to publish a package to Packagist.org, it will have to be able to find the file at the top of your VCS repository. ### The `require` key The first thing you specify in `composer.json` is the [`require`](https://getcomposer.org/doc/04-schema.md.md#require) key. You are telling Composer which packages your project depends on. ```json { "require": { "monolog/monolog": "2.0.*" } } ``` As you can see, [`require`](https://getcomposer.org/doc/04-schema.md.md#require) takes an object that maps **package 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 [`repositories`](https://getcomposer.org/doc/04-schema.md.md#repositories-root-only) key, or in [Packagist.org](https://packagist.org), the default package repository. In the above example, since no other repository has been registered in the `composer.json` file, it is assumed that the `monolog/monolog` package is registered on Packagist.org. (Read more [about Packagist](https://getcomposer.org/doc/01-basic-usage.md.md#packagist), and [about repositories](https://getcomposer.org/doc/05-repositories.md.md)). ### Package names The package name consists of a vendor name and the project's name. Often these will be identical - the vendor name only exists to prevent naming clashes. For example, 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](https://getcomposer.org/doc/02-libraries.md.md). (Note that you can also specify "platform packages" as dependencies, allowing you to require certain versions of server software. See [platform packages](https://getcomposer.org/doc/01-basic-usage.md.md#platform-packages) below.) ### Package version constraints In our example, we are requesting the Monolog package with the version constraint [`2.0.*`](https://semver.madewithlove.com/?package=monolog%2Fmonolog&constraint=2.0.*). This means any version in the `2.0` development branch, or any version that is greater than or equal to 2.0 and less than 2.1 (`>=2.0 <2.1`). Please read [versions](https://getcomposer.org/doc/articles/versions.md.md) for more in-depth information on versions, 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 requested > and searches for it in any repositories that you have registered using the > [`repositories`](https://getcomposer.org/doc/04-schema.md.md#repositories-root-only) key. If you have not registered > any extra repositories, or it does not find a package with that name in the > repositories you have specified, it falls back to Packagist.org (more [below](https://getcomposer.org/doc/01-basic-usage.md.md#packagist)). > > 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 read > about versions and package resolution in the [versions article](https://getcomposer.org/doc/articles/versions.md.md). > **Note:** If you are trying to require a package but Composer throws an error > regarding package stability, the version you have specified may not meet your > default minimum stability requirements. By default, only stable releases are taken > into 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 RC > versions of a package. Read more about stability flags and the `minimum-stability` > key on the [schema page](https://getcomposer.org/doc/04-schema.md.md). ## Installing dependencies To initially install the defined dependencies for your project, you should run the [`update`](https://getcomposer.org/doc/03-cli.md.md#update--u--upgrade) command. ```shell 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 the packages and their exact versions to the `composer.lock` file, locking the project to those specific versions. You should commit the `composer.lock` file to your project repo so that all people working on the project are locked to the same versions of dependencies (more below). This is the main role of the `update` command. - It then implicitly runs the [`install`](https://getcomposer.org/doc/03-cli.md.md#install--i) command. This will download the dependencies' files into the `vendor` directory in your project. (The `vendor` directory is the conventional location for all third-party code in a project). In our example from above, you would end up with the Monolog source files in `vendor/monolog/monolog/`. As Monolog has a dependency on `psr/log`, that package's files can also be found inside `vendor/`. > **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 that > third-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 anyone who sets up the project to use the exact same versions of the dependencies that you are using. Your CI server, production machines, other developers in your team, everything and everyone runs on the same dependencies, which mitigates the potential for bugs affecting only some parts of the deployments. Even if you develop alone, in six months when reinstalling the project you can feel confident that the dependencies installed are still working, even if the dependencies have released many new versions since then. (See note below about using the `update` command.) > **Note:** Libraries should commit the lock file as well, see also: > [Libraries - Lock file](https://getcomposer.org/doc/02-libraries.md.md#lock-file). ### Installing from `composer.lock` If there is already a `composer.lock` file in the project folder, it means either you 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 installs all dependencies that you listed in `composer.json`, but Composer uses the exact versions listed in `composer.lock` to ensure that the package versions are consistent for everyone working on your project. As a result you will have all dependencies requested by your `composer.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 since the file was created). This is by design, ensuring that your project does not break because of unexpected changes in dependencies. So after fetching new changes from your VCS repository it is recommended to run a Composer `install` to make sure the vendor directory is up in sync with your `composer.lock` file. ```shell php composer.phar install ``` Composer enables reproducible builds by default. This means that running the same command multiple times will produce a `vendor/` directory containing files that are identical (*except their timestamps*), including the autoloader files. It is especially beneficial for environments that require strict verification processes, as well as for Linux distributions aiming to package PHP applications in a secure and predictable manner. ## Updating dependencies to their latest versions As mentioned above, the `composer.lock` file prevents you from automatically getting the latest versions of your dependencies. To update to the latest versions, use the [`update`](https://getcomposer.org/doc/03-cli.md.md#update--u--upgrade) command. This will fetch the latest matching versions (according to your `composer.json` file) and update the lock file with the new versions. ```shell php composer.phar update ``` > **Note:** Composer will display a Warning when executing an `install` command > if the `composer.lock` has not been updated since changes were made to the > `composer.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: ```shell php composer.phar update monolog/monolog [...] ``` ## Packagist [Packagist.org](https://packagist.org/) is the main Composer repository. A Composer repository is basically a package source: a place where you can get packages from. Packagist aims to be the central repository that everybody uses. This means 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](https://packagist.org/), you can browse and search for packages. Any open source project using Composer is recommended to publish their packages on 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 are installed on the system but are not actually installable by Composer. This includes PHP itself, PHP extensions and some system libraries. * `php` represents the PHP version of the user, allowing you to apply constraints, e.g. `^7.1`. To require a 64bit version of php, you can require the `php-64bit` package. * `hhvm` represents the version of the HHVM runtime and allows you to apply a constraint, e.g., `^2.3`. * `ext-` allows you to require PHP extensions (includes core extensions). Versioning can be quite inconsistent here, so it's often a good idea to set the constraint to `*`. An example of an extension package name is `ext-gd`. * `lib-` allows constraints to be made on versions of libraries used by PHP. The following are available: `curl`, `iconv`, `icu`, `libxml`, `openssl`, `pcre`, `uuid`, `xsl`. You can use [`show --platform`](https://getcomposer.org/doc/03-cli.md.md#show--info) to get a list of your locally available platform packages. ## Autoloading For libraries that specify autoload information, Composer generates a `vendor/autoload.php` file. You can include this file and start using the classes that those libraries provide without any extra work: ```php 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 an [`autoload`](https://getcomposer.org/doc/04-schema.md.md#autoload) field to `composer.json`. ```json { "autoload": { "psr-4": {"Acme\\": "src/"} } } ``` Composer will register a [PSR-4](https://www.php-fig.org/psr/psr-4/) autoloader for the `Acme` namespace. You define a mapping from namespaces to directories. The `src` directory would be in your project root, on the same level as the `vendor` directory. An example filename would be `src/Foo.php` containing an `Acme\Foo` class. After adding the [`autoload`](https://getcomposer.org/doc/04-schema.md.md#autoload) field, you have to re-run this command: ```shell php composer.phar dump-autoload ``` This command will re-generate the `vendor/autoload.php` file. See the [`dump-autoload`](https://getcomposer.org/doc/03-cli.md.md#dump-autoload--dumpautoload) section for more information. Including that file will also return the autoloader instance, so you can store the 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. ```php $loader = require __DIR__ . '/vendor/autoload.php'; $loader->addPsr4('Acme\\Test\\', __DIR__); ``` In addition to PSR-4 autoloading, Composer also supports PSR-0, classmap and files autoloading. See the [`autoload`](https://getcomposer.org/doc/04-schema.md.md#autoload) reference for more information. See also the docs on [optimizing the autoloader](https://getcomposer.org/doc/articles/autoloader-optimization.md.md). > **Note:** Composer provides its own autoloader. If you don't want to use that > one, you can include `vendor/composer/autoload_*.php` files, which return > associative arrays allowing you to configure your own autoloader. ← [Intro](https://getcomposer.org/doc/00-intro.md.md) | [Libraries](https://getcomposer.org/doc/02-libraries.md.md) → --- Source: https://getcomposer.org/doc/02-libraries.md # Libraries This chapter will tell you how to make your library installable through Composer. ## Every project is a package As soon as you have a `composer.json` in a directory, that directory is a package. When you add a [`require`](https://getcomposer.org/doc/04-schema.md.md#require) to a project, you are making a package that depends on other packages. The only difference between your project and a library is that your project is a package without a name. In order to make that package installable you need to give it a name. You do this by adding the [`name`](https://getcomposer.org/doc/04-schema.md.md#name) property in `composer.json`: ```json { "name": "acme/hello-world", "require": { "monolog/monolog": "1.0.*" } } ``` In this case the project name is `acme/hello-world`, where `acme` is the vendor name. Supplying a vendor name is mandatory. > **Note:** If you don't know what to use as a vendor name, your GitHub > username is usually a good bet. Package names must be lowercase, and the > convention is to use dashes for word separation. ## Library Versioning In the vast majority of cases, you will be maintaining your library using some sort of version control system like git, svn, hg or fossil. In these cases, Composer infers versions from your VCS, and you **should not** specify a version in your `composer.json` file. (See the [Versions article](https://getcomposer.org/doc/articles/versions.md.md) to learn about how Composer uses VCS branches and tags to resolve version constraints.) If you are maintaining packages by hand (i.e., without a VCS), you'll need to specify the version explicitly by adding a `version` value in your `composer.json` file: ```json { "version": "1.0.0" } ``` > **Note:** When you add a hardcoded version to a VCS, the version will conflict > with tag names. Composer will not be able to determine the version number. ### VCS Versioning Composer uses your VCS's branch and tag features to resolve the version constraints you specify in your [`require`](https://getcomposer.org/doc/04-schema.md.md#require) field to specific sets of files. When determining valid available versions, Composer looks at all of your tags and branches and translates their names into an internal list of options that it then matches against the version constraint you provided. For more on how Composer treats tags and branches and how it resolves package version constraints, read the [versions](https://getcomposer.org/doc/articles/versions.md.md) article. ## Lock file For your library it is **recommended to commit the `composer.lock` file**. This helps your team to always test against the same dependency versions, and it can help prevent supply chain attacks from propagating, as newly published (possibly malicious) dependency versions are not pulled into your CI or development environment until you explicitly update. This protection only covers working on the library itself. The lock file has no effect on projects that depend on your library, they install whatever versions your constraints allow. You can therefore exclude it from dist archives using `export-ignore`, see [Light-weight distribution packages](https://getcomposer.org/doc/02-libraries.md.md#light-weight-distribution-packages). As your users will not get the locked versions, keep the lock file up to date and also run CI jobs with `composer update` (and `composer update --prefer-lowest`) to catch breakage from new releases or too low lower bounds. As these jobs install unlocked versions, consider configuring a [cooldown](https://getcomposer.org/doc/06-config.md.md#cooldown), do not give them access to secrets or write permissions (e.g. to your repository), and do not run `composer update` in any build or release steps. ## Publishing to a VCS Once you have a VCS repository (version control system, e.g. git) containing a `composer.json` file, your library is already composer-installable. In this example we will publish the `acme/hello-world` library on GitHub under `github.com/username/hello-world`. Now, to test installing the `acme/hello-world` package, we create a new project locally. We will call it `acme/blog`. This blog will depend on `acme/hello-world`, which in turn depends on `monolog/monolog`. We can accomplish this by creating a new `blog` directory somewhere, containing a `composer.json`: ```json { "name": "acme/blog", "require": { "acme/hello-world": "dev-master" } } ``` The name is not needed in this case, since we don't want to publish the blog as a library. It is added here to clarify which `composer.json` is being described. Now we need to tell the blog app where to find the `hello-world` dependency. We do this by adding a package repository specification to the blog's `composer.json`: ```json { "name": "acme/blog", "repositories": [ { "type": "vcs", "url": "https://github.com/username/hello-world" } ], "require": { "acme/hello-world": "dev-master" } } ``` For more details on how package repositories work and what other types are available, see [Repositories](https://getcomposer.org/doc/05-repositories.md.md). That's all. You can now install the dependencies by running Composer's [`install`](https://getcomposer.org/doc/03-cli.md.md#install--i) command! **Recap:** Any git/svn/hg/fossil repository containing a `composer.json` can be added to your project by specifying the package repository and declaring the dependency in the [`require`](https://getcomposer.org/doc/04-schema.md.md#require) field. ## Publishing to packagist Alright, so now you can publish packages. But specifying the VCS repository every time is cumbersome. You don't want to force all your users to do that. The other thing that you may have noticed is that we did not specify a package repository for `monolog/monolog`. How did that work? The answer is Packagist. [Packagist](https://packagist.org/) is the main package repository for Composer, and it is enabled by default. Anything that is published on Packagist is available automatically through Composer. Since [Monolog is on Packagist](https://packagist.org/packages/monolog/monolog), we can depend on it without having to specify any additional repositories. If we wanted to share `hello-world` with the world, we would publish it on Packagist as well. You visit [Packagist](https://packagist.org) and hit the "Submit" button. This will prompt you to sign up if you haven't already, and then allows you to submit the URL to your VCS repository, at which point Packagist will start crawling it. Once it is done, your package will be available to anyone! ## Light-weight distribution packages Some useless information like the `.github` directory, or large examples, test data, etc. should typically not be included in distributed packages. The `.gitattributes` file is a git specific file like `.gitignore` also living at the root directory of your library. It overrides local and global configuration (`.git/config` and `~/.gitconfig` respectively) when present and tracked by git. Use `.gitattributes` to prevent unwanted files from bloating the zip distribution packages. ```text // .gitattributes /demo export-ignore phpunit.xml.dist export-ignore /.github/ export-ignore /composer.lock export-ignore ``` Test it by inspecting the zip file generated manually: ```shell git archive branchName --format zip -o file.zip ``` > **Note:** Files would be still tracked by git just not included in the > zip distribution. This only works for packages installed from > dist (i.e. tagged releases) coming from GitHub, GitLab or Bitbucket. ← [Basic usage](https://getcomposer.org/doc/01-basic-usage.md.md) | [Command-line interface](https://getcomposer.org/doc/03-cli.md.md) → --- Source: https://getcomposer.org/doc/03-cli.md # Command-line interface / Commands You've already learned how to use the command-line interface to do some things. This chapter documents all the available commands. To get help from the command-line, call `composer` or `composer list` to see the complete list of commands, then `--help` combined with any of those can give you more information. As Composer uses [symfony/console](https://github.com/symfony/console) you can call commands by short name if it's not ambiguous. ```shell php composer.phar dump ``` calls `composer dump-autoload`. ## Bash Completions To install bash completions you can run `composer completion bash > completion.bash`. This will create a `completion.bash` file in the current directory. Then execute `source completion.bash` to enable it in the current terminal session. Move and rename the `completion.bash` file to `/etc/bash_completion.d/composer` to make it load automatically in new terminals. ## Global Options The following options are available with every command: * **--verbose (-v):** Increase verbosity of messages. * **--help (-h):** Display help information. * **--quiet (-q):** Do not output any message. * **--no-interaction (-n):** Do not ask any interactive question. * **--no-plugins:** Disables plugins. * **--no-scripts:** Skips execution of scripts defined in `composer.json`. * **--no-cache:** Disables the use of the cache directory. Same as setting the COMPOSER_CACHE_DIR env var to /dev/null (or NUL on Windows). * **--working-dir (-d):** If specified, use the given directory as working directory. * **--profile:** Display timing and memory usage information * **--ansi:** Force ANSI output. * **--no-ansi:** Disable ANSI output. * **--version (-V):** Display this application version. ## Process Exit Codes * **0:** OK * **1:** Generic/unknown error code * **2:** Dependency solving error code ## init In the [Libraries](https://getcomposer.org/doc/02-libraries.md.md) chapter we looked at how to create a `composer.json` by hand. There is also an `init` command available to do this. When you run the command it will interactively ask you to fill in the fields, while using some smart defaults. ```shell php composer.phar init ``` ### Options * **--name:** Name of the package. * **--description:** Description of the package. * **--author:** Author name of the package. * **--type:** Type of package. * **--homepage:** Homepage of the package. * **--require:** Package to require with a version constraint. Should be in format `foo/bar:1.0.0`. * **--require-dev:** Development requirements, see **--require**. * **--stability (-s):** Value for the `minimum-stability` field. * **--license (-l):** License of package. * **--repository:** Provide one (or more) custom repositories. They will be stored in the generated composer.json, and used for auto-completion when prompting for the list of requires. Every repository can be either an HTTP URL pointing to a `composer` repository or a JSON string which is similar to what the [repositories](https://getcomposer.org/doc/04-schema.md.md#repositories-root-only) key accepts. * **--autoload (-a):** Add a PSR-4 autoload mapping to the composer.json. Automatically maps your package's namespace to the provided directory. (Expects a relative path, e.g. src/) See also [PSR-4 autoload](https://getcomposer.org/doc/04-schema.md.md#psr-4). ## install / i The `install` command reads the `composer.json` file from the current directory, resolves the dependencies, and installs them into `vendor`. ```shell php composer.phar install ``` If there is a `composer.lock` file in the current directory, it will use the exact versions from there instead of resolving them. This ensures that everyone using the library will get the same versions of the dependencies. If there is no `composer.lock` file, Composer will create one after dependency resolution. ### Options * **--prefer-install:** There are two ways of downloading a package: `source` and `dist`. Composer uses `dist` by default. If you pass `--prefer-install=source` (or `--prefer-source`) Composer will install from `source` if there is one. This is useful if you want to make a bugfix to a project and get a local git clone of the dependency directly. To get the legacy behavior where Composer use `source` automatically for dev versions of packages, use `--prefer-install=auto`. See also [config.preferred-install](https://getcomposer.org/doc/06-config.md.md#preferred-install). Passing this flag will override the config value. * **--dry-run:** If you want to run through an installation without actually installing a package, you can use `--dry-run`. This will simulate the installation and show you what would happen. * **--download-only:** Download only, do not install packages. * **--dev:** Install packages listed in `require-dev` (this is the default behavior). * **--no-dev:** Skip installing packages listed in `require-dev`. The autoloader generation skips the `autoload-dev` rules. Also see [COMPOSER_NO_DEV](https://getcomposer.org/doc/03-cli.md.md#composer_no_dev). * **--no-autoloader:** Skips autoloader generation. * **--no-progress:** Removes the progress display that can mess with some terminals or scripts which don't handle backspace characters. * **--audit:** Run an audit after installation is complete. * **--audit-format:** Audit output format. Must be "table", "plain", "json", or "summary" (default). * **--no-security-blocking:** DEPRECATED, use `--no-blocking` instead. Allows installing packages with security advisories, that are abandoned or that are still in the cooldown period. Also see [COMPOSER_NO_SECURITY_BLOCKING](https://getcomposer.org/doc/03-cli.md.md#composer_no_security_blocking). * **--no-blocking:** Disables all policy based dependency blocking during this command, including the cooldown period. Also see [COMPOSER_NO_BLOCKING](https://getcomposer.org/doc/03-cli.md.md#composer_no_blocking). * **--optimize-autoloader (-o):** Convert PSR-0/4 autoloading to classmap to get a faster autoloader. This is recommended especially for production, but can take a bit of time to run so it is currently not done by default. * **--classmap-authoritative (-a):** Autoload classes from the classmap only. Implicitly enables `--optimize-autoloader`. * **--strict-psr-autoloader:** Return a failed exit code (6) if PSR-4 or PSR-0 mapping errors are present in the current project (dependencies excluded). Requires `--optimize-autoloader` or `--classmap-authoritative` to work. * **--apcu-autoloader:** Use APCu to cache found/not-found classes. * **--apcu-autoloader-prefix:** Use a custom prefix for the APCu autoloader cache. Implicitly enables `--apcu-autoloader`. * **--ignore-platform-reqs:** ignore all platform requirements (`php`, `hhvm`, `lib-*` and `ext-*`) and force the installation even if the local machine does not fulfill these. See also the [`platform`](https://getcomposer.org/doc/06-config.md.md#platform) config option. * **--ignore-platform-req:** ignore a specific platform requirement(`php`, `hhvm`, `lib-*` and `ext-*`) and force the installation even if the local machine does not fulfill it. Multiple requirements can be ignored via wildcard. Appending a `+` makes it only ignore the upper-bound of the requirements. For example, if a package requires `php: ^7`, then the option `--ignore-platform-req=php+` would allow installing on PHP 8, but installation on PHP 5.6 would still fail. ## update / u / upgrade In order to get the latest versions of the dependencies and to update the `composer.lock` file, you should use the `update` command. This command is also aliased as `upgrade` as it does the same as `upgrade` does if you are thinking of `apt-get` or similar package managers. ```shell php composer.phar update ``` This will resolve all dependencies of the project and write the exact versions into `composer.lock`. If you only want to update a few packages and not all, you can list them as such: ```shell php composer.phar update vendor/package vendor/package2 ``` You can also use wildcards to update a bunch of packages at once: ```shell php composer.phar update "vendor/*" ``` If you want to downgrade a package to a specific version without changing your composer.json you can use `--with` and provide a custom version constraint: ```shell php composer.phar update --with vendor/package:2.0.1 ``` Note that with the above all packages will be updated. If you only want to update the package(s) for which you provide custom constraints using `--with`, you can skip `--with` and instead use constraints with the partial update syntax: ```shell php composer.phar update vendor/package:2.0.1 vendor/package2:3.0.* ``` > **Note:** For packages also required in your composer.json the custom constraint > must be a subset of the existing constraint. The composer.json constraints still > apply and the composer.json is not modified by these temporary update constraints. ### Options * **--prefer-install:** There are two ways of downloading a package: `source` and `dist`. Composer uses `dist` by default. If you pass `--prefer-install=source` (or `--prefer-source`) Composer will install from `source` if there is one. This is useful if you want to make a bugfix to a project and get a local git clone of the dependency directly. To get the legacy behavior where Composer use `source` automatically for dev versions of packages, use `--prefer-install=auto`. See also [config.preferred-install](https://getcomposer.org/doc/06-config.md.md#preferred-install). Passing this flag will override the config value. * **--dry-run:** Simulate the command without actually doing anything. * **--dev:** Install packages listed in `require-dev` (this is the default behavior). * **--no-dev:** Skip installing packages listed in `require-dev`. The autoloader generation skips the `autoload-dev` rules. Also see [COMPOSER_NO_DEV](https://getcomposer.org/doc/03-cli.md.md#composer_no_dev). * **--no-install:** Does not run the install step after updating the composer.lock file. * **--no-audit:** Does not run the audit steps after updating the composer.lock file. Also see [COMPOSER_NO_AUDIT](https://getcomposer.org/doc/03-cli.md.md#composer_no_audit). * **--audit-format:** Audit output format. Must be "table", "plain", "json", or "summary" (default). * **--no-security-blocking:** DEPRECATED, use `--no-blocking` instead. Allows installing packages with security advisories, that are abandoned or that are still in the cooldown period. Also see [COMPOSER_NO_SECURITY_BLOCKING](https://getcomposer.org/doc/03-cli.md.md#composer_no_security_blocking). * **--no-blocking:** Disables all policy based dependency blocking during this command, including the cooldown period. Also see [COMPOSER_NO_BLOCKING](https://getcomposer.org/doc/03-cli.md.md#composer_no_blocking). * **--no-cooldown:** Disables the [cooldown policy](https://getcomposer.org/doc/06-config.md.md#cooldown) blocking during this command, other policies still apply. * **--lock:** Overwrites the lock file hash to suppress warning about the lock file being out of date without updating package versions. Package metadata like mirrors and URLs are updated if they changed. * **--with:** Temporary version constraint to add, e.g. foo/bar:1.0.0 or foo/bar=1.0.0 * **--no-autoloader:** Skips autoloader generation. * **--no-progress:** Removes the progress display that can mess with some terminals or scripts which don't handle backspace characters. * **--with-dependencies (-w):** Update also dependencies of packages in the argument list, except those which are root requirements. Can also be set via the COMPOSER_WITH_DEPENDENCIES=1 env var. * **--with-all-dependencies (-W):** Update also dependencies of packages in the argument list, including those which are root requirements. Can also be set via the COMPOSER_WITH_ALL_DEPENDENCIES=1 env var. * **--optimize-autoloader (-o):** Convert PSR-0/4 autoloading to classmap to get a faster autoloader. This is recommended especially for production, but can take a bit of time to run, so it is currently not done by default. * **--classmap-authoritative (-a):** Autoload classes from the classmap only. Implicitly enables `--optimize-autoloader`. * **--strict-psr-autoloader:** Return a failed exit code (6) if PSR-4 or PSR-0 mapping errors are present in the current project (dependencies excluded). Requires `--optimize-autoloader` or `--classmap-authoritative` to work. * **--apcu-autoloader:** Use APCu to cache found/not-found classes. * **--apcu-autoloader-prefix:** Use a custom prefix for the APCu autoloader cache. Implicitly enables `--apcu-autoloader`. * **--ignore-platform-reqs:** ignore all platform requirements (`php`, `hhvm`, `lib-*` and `ext-*`) and force the installation even if the local machine does not fulfill these. See also the [`platform`](https://getcomposer.org/doc/06-config.md.md#platform) config option. * **--ignore-platform-req:** ignore a specific platform requirement(`php`, `hhvm`, `lib-*` and `ext-*`) and force the installation even if the local machine does not fulfill it. Multiple requirements can be ignored via wildcard. Appending a `+` makes it only ignore the upper-bound of the requirements. For example, if a package requires `php: ^7`, then the option `--ignore-platform-req=php+` would allow installing on PHP 8, but installation on PHP 5.6 would still fail. * **--prefer-stable:** Prefer stable versions of dependencies. Can also be set via the COMPOSER_PREFER_STABLE=1 env var. * **--prefer-lowest:** Prefer lowest versions of dependencies. Useful for testing minimal versions of requirements, generally used with `--prefer-stable`. Can also be set via the COMPOSER_PREFER_LOWEST=1 env var. * **--minimal-changes (-m):** Only perform absolutely necessary changes to dependencies. If packages cannot be kept at their currently locked version they are updated. For partial updates the allow-listed packages are always updated fully. Can also be set via the COMPOSER_MINIMAL_CHANGES=1 env var. * **--patch-only:** Only allow patch version updates for currently installed dependencies. * **--interactive:** Interactive interface with autocompletion to select the packages to update. * **--root-reqs:** Restricts the update to your first degree dependencies. * **--bump-after-update:** Runs `bump` after performing the update. Set to `dev` or `no-dev` to only bump those dependencies. Specifying one of the words `mirrors`, `lock`, or `nothing` as an argument has the same effect as specifying the option `--lock`, for example `composer update mirrors` is exactly the same as `composer update --lock`. ## require / r The `require` command adds new packages to the `composer.json` file from the current directory. If no file exists one will be created on the fly. If you do not specify a package, Composer will prompt you to search for a package, and given results, provide a list of matches to require. ```shell php composer.phar require ``` After adding/changing the requirements, the modified requirements will be installed or updated. If you do not want to choose requirements interactively, you can pass them to the command. ```shell php composer.phar require "vendor/package:2.*" vendor/package2:dev-master ``` If you do not specify a version constraint, composer will choose a suitable one based on the available package versions. ```shell php composer.phar require vendor/package vendor/package2 ``` If you do not want to install the new dependencies immediately you can call it with --no-update ### Options * **--dev:** Add packages to `require-dev`. * **--dry-run:** Simulate the command without actually doing anything. * **--prefer-install:** There are two ways of downloading a package: `source` and `dist`. Composer uses `dist` by default. If you pass `--prefer-install=source` (or `--prefer-source`) Composer will install from `source` if there is one. This is useful if you want to make a bugfix to a project and get a local git clone of the dependency directly. To get the legacy behavior where Composer use `source` automatically for dev versions of packages, use `--prefer-install=auto`. See also [config.preferred-install](https://getcomposer.org/doc/06-config.md.md#preferred-install). Passing this flag will override the config value. * **--no-progress:** Removes the progress display that can mess with some terminals or scripts which don't handle backspace characters. * **--no-update:** Disables the automatic update of the dependencies (implies --no-install). * **--no-install:** Does not run the install step after updating the composer.lock file. * **--no-audit:** Does not run the audit steps after updating the composer.lock file. Also see [COMPOSER_NO_AUDIT](https://getcomposer.org/doc/03-cli.md.md#composer_no_audit). * **--audit-format:** Audit output format. Must be "table", "plain", "json", or "summary" (default). * **--no-security-blocking:** DEPRECATED, use `--no-blocking` instead. Allows installing packages with security advisories, that are abandoned or that are still in the cooldown period. Also see [COMPOSER_NO_SECURITY_BLOCKING](https://getcomposer.org/doc/03-cli.md.md#composer_no_security_blocking). * **--no-blocking:** Disables all policy blocking during this command, including the cooldown period. Also see [COMPOSER_NO_BLOCKING](https://getcomposer.org/doc/03-cli.md.md#composer_no_blocking). * **--no-cooldown:** Disables the [cooldown policy](https://getcomposer.org/doc/06-config.md.md#cooldown) blocking during this command, other policies still apply. * **--update-no-dev:** Run the dependency update with the `--no-dev` option. Also see [COMPOSER_NO_DEV](https://getcomposer.org/doc/03-cli.md.md#composer_no_dev). * **--update-with-dependencies (-w):** Also update dependencies of the newly required packages, except those that are root requirements. Can also be set via the COMPOSER_WITH_DEPENDENCIES=1 env var. * **--update-with-all-dependencies (-W):** Also update dependencies of the newly required packages, including those that are root requirements. Can also be set via the COMPOSER_WITH_ALL_DEPENDENCIES=1 env var. * **--ignore-platform-reqs:** ignore all platform requirements (`php`, `hhvm`, `lib-*` and `ext-*`) and force the installation even if the local machine does not fulfill these. See also the [`platform`](https://getcomposer.org/doc/06-config.md.md#platform) config option. * **--ignore-platform-req:** ignore a specific platform requirement(`php`, `hhvm`, `lib-*` and `ext-*`) and force the installation even if the local machine does not fulfill it. Multiple requirements can be ignored via wildcard. * **--prefer-stable:** Prefer stable versions of dependencies. Can also be set via the COMPOSER_PREFER_STABLE=1 env var. * **--prefer-lowest:** Prefer lowest versions of dependencies. Useful for testing minimal versions of requirements, generally used with `--prefer-stable`. Can also be set via the COMPOSER_PREFER_LOWEST=1 env var. * **--minimal-changes (-m):** During an update with `-w`/`-W`, only perform absolutely necessary changes to transitive dependencies. Can also be set via the COMPOSER_MINIMAL_CHANGES=1 env var. * **--sort-packages:** Keep packages sorted in `composer.json`. * **--fixed:** When no version constraint is given, write the exact version that was picked to `composer.json` instead of the recommended constraint. Only allowed when the root package's type is `project`, or together with `--dev`. * **--optimize-autoloader (-o):** Convert PSR-0/4 autoloading to classmap to get a faster autoloader. This is recommended especially for production, but can take a bit of time to run, so it is currently not done by default. * **--classmap-authoritative (-a):** Autoload classes from the classmap only. Implicitly enables `--optimize-autoloader`. * **--apcu-autoloader:** Use APCu to cache found/not-found classes. * **--apcu-autoloader-prefix:** Use a custom prefix for the APCu autoloader cache. Implicitly enables `--apcu-autoloader`. ## remove / rm / uninstall The `remove` command removes packages from the `composer.json` file from the current directory. ```shell php composer.phar remove vendor/package vendor/package2 ``` After removing the requirements, the modified requirements will be uninstalled. ### Options * **--unused:** Remove unused packages that are not a direct or indirect dependency (anymore). * **--dev:** Remove packages from `require-dev`. * **--dry-run:** Simulate the command without actually doing anything. * **--no-progress:** Removes the progress display that can mess with some terminals or scripts which don't handle backspace characters. * **--no-update:** Disables the automatic update of the dependencies (implies --no-install). * **--no-install:** Does not run the install step after updating the composer.lock file. * **--no-audit:** Does not run the audit steps after installation is complete. Also see [COMPOSER_NO_AUDIT](https://getcomposer.org/doc/03-cli.md.md#composer_no_audit). * **--audit-format:** Audit output format. Must be "table", "plain", "json", or "summary" (default). * **--no-security-blocking:** DEPRECATED, use `--no-blocking` instead. Allows installing packages with security advisories, that are abandoned or that are still in the cooldown period. Also see [COMPOSER_NO_SECURITY_BLOCKING](https://getcomposer.org/doc/03-cli.md.md#composer_no_security_blocking). * **--no-blocking:** Disables all policy based dependency blocking during this command, including the cooldown period. Also see [COMPOSER_NO_BLOCKING](https://getcomposer.org/doc/03-cli.md.md#composer_no_blocking). * **--no-cooldown:** Disables the [cooldown policy](https://getcomposer.org/doc/06-config.md.md#cooldown) blocking during this command, other policies still apply. * **--update-no-dev:** Run the dependency update with the --no-dev option. Also see [COMPOSER_NO_DEV](https://getcomposer.org/doc/03-cli.md.md#composer_no_dev). * **--update-with-dependencies (-w):** Also update dependencies of the removed packages. Can also be set via the COMPOSER_WITH_DEPENDENCIES=1 env var. (Deprecated, is now default behavior) * **--update-with-all-dependencies (-W):** Allows all inherited dependencies to be updated, including those that are root requirements. Can also be set via the COMPOSER_WITH_ALL_DEPENDENCIES=1 env var. * **--minimal-changes (-m):** During an update with `-w`/`-W`, only perform absolutely necessary changes to transitive dependencies. Can also be set via the COMPOSER_MINIMAL_CHANGES=1 env var. * **--ignore-platform-reqs:** ignore all platform requirements (`php`, `hhvm`, `lib-*` and `ext-*`) and force the installation even if the local machine does not fulfill these. See also the [`platform`](https://getcomposer.org/doc/06-config.md.md#platform) config option. * **--ignore-platform-req:** ignore a specific platform requirement(`php`, `hhvm`, `lib-*` and `ext-*`) and force the installation even if the local machine does not fulfill it. Multiple requirements can be ignored via wildcard. * **--optimize-autoloader (-o):** Convert PSR-0/4 autoloading to classmap to get a faster autoloader. This is recommended especially for production, but can take a bit of time to run so it is currently not done by default. * **--classmap-authoritative (-a):** Autoload classes from the classmap only. Implicitly enables `--optimize-autoloader`. * **--apcu-autoloader:** Use APCu to cache found/not-found classes. * **--apcu-autoloader-prefix:** Use a custom prefix for the APCu autoloader cache. Implicitly enables `--apcu-autoloader`. ## bump The `bump` command increases the lower limit of your composer.json requirements to the currently installed versions. This helps to ensure your dependencies do not accidentally get downgraded due to some other conflict, and can slightly improve dependency resolution performance as it limits the amount of package versions Composer has to look at. Running this blindly on libraries is **NOT** recommended as it will narrow down your allowed dependencies, which may cause dependency hell for your users. Running it with `--dev-only` on libraries may be fine however as dev requirements are local to the library and do not affect consumers of the package. ### Options * **--dev-only:** Only bump requirements in "require-dev". * **--no-dev-only:** Only bump requirements in "require". * **--dry-run:** Outputs the packages to bump, but will not execute anything. ## reinstall The `reinstall` command looks up installed packages by name (or by type with `--type`), uninstalls them and reinstalls them. This lets you do a clean install of a package if you messed with its files, or if you wish to change the installation type using --prefer-install. ```shell php composer.phar reinstall acme/foo acme/bar ``` You can specify more than one package name to reinstall, or use a wildcard to select several packages at once: ```shell php composer.phar reinstall "acme/*" ``` To reinstall every installed package of a given type, use `--type` instead: ```shell php composer.phar reinstall --type=composer-plugin ``` ### Options * **--type:** Reinstall all installed packages of the given type, e.g. `--type=library`. The type must match exactly, wildcards are not supported. Can be passed more than once. It can't be combined with package names. * **--prefer-install:** There are two ways of downloading a package: `source` and `dist`. Composer uses `dist` by default. If you pass `--prefer-install=source` (or `--prefer-source`) Composer will install from `source` if there is one. This is useful if you want to make a bugfix to a project and get a local git clone of the dependency directly. To get the legacy behavior where Composer use `source` automatically for dev versions of packages, use `--prefer-install=auto`. See also [config.preferred-install](https://getcomposer.org/doc/06-config.md.md#preferred-install). Passing this flag will override the config value. * **--no-autoloader:** Skips autoloader generation. * **--no-progress:** Removes the progress display that can mess with some terminals or scripts which don't handle backspace characters. * **--optimize-autoloader (-o):** Convert PSR-0/4 autoloading to classmap to get a faster autoloader. This is recommended especially for production, but can take a bit of time to run so it is currently not done by default. * **--classmap-authoritative (-a):** Autoload classes from the classmap only. Implicitly enables `--optimize-autoloader`. * **--apcu-autoloader:** Use APCu to cache found/not-found classes. * **--apcu-autoloader-prefix:** Use a custom prefix for the APCu autoloader cache. Implicitly enables `--apcu-autoloader`. * **--ignore-platform-reqs:** ignore all platform requirements. This only has an effect in the context of the autoloader generation for the reinstall command. * **--ignore-platform-req:** ignore a specific platform requirement. This only has an effect in the context of the autoloader generation for the reinstall command. Multiple requirements can be ignored via wildcard. ## check-platform-reqs The check-platform-reqs command checks that your PHP and extensions versions match the platform requirements of the installed packages. This can be used to verify that a production server has all the extensions needed to run a project after installing it for example. Unlike update/install, this command will ignore config.platform settings and check the real platform packages so you can be certain you have the required platform dependencies. ### Options * **--lock:** Checks requirements only from the lock file, not from installed packages. * **--no-dev:** Disables checking of require-dev packages requirements. * **--format (-f):** Format of the output: text (default) or json ## global The global command allows you to run other commands like `install`, `remove`, `require` or `update` as if you were running them from the [COMPOSER_HOME](https://getcomposer.org/doc/03-cli.md.md#composer_home) directory. This is merely a helper to manage a project stored in a central location that can hold CLI tools or Composer plugins that you want to have available everywhere. This can be used to install CLI utilities globally. Here is an example: ```shell php composer.phar global require friendsofphp/php-cs-fixer ``` Now the `php-cs-fixer` binary is available globally. Make sure your global [vendor binaries](https://getcomposer.org/doc/articles/vendor-binaries.md.md) directory is in your `$PATH` environment variable, you can get its location with the following command : ```shell php composer.phar global config bin-dir --absolute ``` If you wish to update the binary later on you can run a global update: ```shell php composer.phar global update ``` ## search The search command allows you to search through the current project's package repositories. Usually this will be packagist. You pass it the terms you want to search for. ```shell php composer.phar search monolog ``` You can also search for more than one term by passing multiple arguments. ### Options * **--only-name (-N):** Search only in package names. * **--only-vendor (-O):** Search only for vendor / organization names, returns only "vendor" as a result. * **--type (-t):** Search for a specific package type. * **--format (-f):** Lets you pick between text (default) or json output format. Note that in the json, only the name and description keys are guaranteed to be present. The rest (`url`, `repository`, `downloads` and `favers`) are available for Packagist.org search results and other repositories may return more or less data. ## show / info To list all of the available packages, you can use the `show` command. ```shell php composer.phar show ``` To filter the list you can pass a package mask using wildcards. ```shell php composer.phar show "monolog/*" ``` ```text monolog/monolog 2.4.0 Sends your logs to files, sockets, inboxes, databases and various web services ``` If you want to see the details of a certain package, you can pass the package name. ```shell php composer.phar show monolog/monolog ``` ```text name : monolog/monolog descrip. : Sends your logs to files, sockets, inboxes, databases and various web services keywords : log, logging, psr-3 versions : * 1.27.1 type : library license : MIT License (MIT) (OSI approved) https://spdx.org/licenses/MIT.html#licenseText homepage : http://github.com/Seldaek/monolog source : [git] https://github.com/Seldaek/monolog.git 904713c5929655dc9b97288b69cfeedad610c9a1 dist : [zip] https://api.github.com/repos/Seldaek/monolog/zipball/904713c5929655dc9b97288b69cfeedad610c9a1 904713c5929655dc9b97288b69cfeedad610c9a1 names : monolog/monolog, psr/log-implementation support issues : https://github.com/Seldaek/monolog/issues source : https://github.com/Seldaek/monolog/tree/1.27.1 autoload psr-4 Monolog\ => src/Monolog requires php >=5.3.0 psr/log ~1.0 ``` You can even pass the package version, which will tell you the details of that specific version. ```shell php composer.phar show monolog/monolog 1.0.2 ``` ### Options * **--all:** List all packages available in all your repositories. * **--installed (-i):** List the packages that are installed (this is enabled by default, and deprecated). * **--locked:** List the locked packages from composer.lock. * **--platform (-p):** List only platform packages (php & extensions). * **--available (-a):** List available packages only. * **--self (-s):** List the root package info. * **--name-only (-N):** List package names only. * **--path (-P):** List package paths. * **--tree (-t):** List your dependencies as a tree. If you pass a package name it will show the dependency tree for that package. * **--latest (-l):** List all installed packages including their latest version. * **--outdated (-o):** Implies --latest, but this lists *only* packages that have a newer version available. * **--ignore:** Ignore specified package(s). Can contain wildcards (`*`). Use it with the --outdated option if you don't want to be informed about new versions of some packages * **--no-dev:** Filters dev dependencies from the package list. * **--major-only (-M):** Use with --latest or --outdated. Only shows packages that have major SemVer-compatible updates. * **--minor-only (-m):** Use with --latest or --outdated. Only shows packages that have minor SemVer-compatible updates. * **--patch-only:** Use with --latest or --outdated. Only shows packages that have patch-level SemVer-compatible updates. * **--sort-by-age (-A):** Displays the installed version's age, and sorts packages oldest first. Use with the --latest or --outdated option. * **--cooldown-period:** Overrides the configured [policy.cooldown.period](https://getcomposer.org/doc/06-config.md.md#period) while looking up latest versions, even when the policy is disabled or not blocking; `0` disables it for this run. Use with the --latest or --outdated option. * **--direct (-D):** Restricts the list of packages to your direct dependencies. * **--strict:** Return a non-zero exit code when there are outdated packages. * **--format (-f):** Lets you pick between text (default) or json output format. * **--ignore-platform-reqs:** ignore all platform requirements (`php`, `hhvm`, `lib-*` and `ext-*`) and force the installation even if the local machine does not fulfill these. Use with the --outdated option. * **--ignore-platform-req:** ignore a specific platform requirement(`php`, `hhvm`, `lib-*` and `ext-*`) and force the installation even if the local machine does not fulfill it. Multiple requirements can be ignored via wildcard. Use with the --outdated option. ## outdated The `outdated` command shows a list of installed packages that have updates available, including their current and latest versions. This is basically an alias for `composer show -lo`. The color coding is as such: - **green (=)**: Dependency is in the latest version and is up to date. - **yellow (`~`)**: Dependency has a new version available that includes backwards compatibility breaks according to semver, so upgrade when you can but it may involve work. - **red (!)**: Dependency has a new version that is semver-compatible and you should upgrade it. - **uncolored (c)**: Dependency has a newer version that is still in the [cooldown period](https://getcomposer.org/doc/06-config.md.md#cooldown) and cannot be installed yet; the time left is shown next to it. Such packages are listed, but do not count as outdated for `--strict`. When a cooldown period is configured, the latest version shown is the newest one the cooldown policy allows installing, so the output matches what `composer update` would do. A newer release still in the cooldown period is shown next to it with the time left, or in its place once you are on the newest installable version. When several are waiting, the one that becomes installable first is shown. A dependency whose versions all have platform requirements your platform cannot satisfy is considered up to date, as there is nothing it can be updated to. A dependency that is not found in any repository is shown as `[none matched]` and counts as outdated for `--strict`. ### Options * **--all (-a):** Show all packages, not just outdated (alias for `composer show --latest`). * **--direct (-D):** Restricts the list of packages to your direct dependencies. * **--strict:** Returns non-zero exit code if any package is outdated. * **--ignore:** Ignore specified package(s). Can contain wildcards (`*`). Use it if you don't want to be informed about new versions of some packages * **--major-only (-M):** Only shows packages that have major SemVer-compatible updates. * **--minor-only (-m):** Only shows packages that have minor SemVer-compatible updates. * **--patch-only (-p):** Only shows packages that have patch-level SemVer-compatible updates. * **--sort-by-age (-A):** Displays the installed version's age, and sorts packages oldest first. * **--cooldown-period:** Overrides the configured [policy.cooldown.period](https://getcomposer.org/doc/06-config.md.md#period), even when the policy is disabled or not blocking; `0` shows the newest releases regardless of the cooldown policy. * **--format (-f):** Lets you pick between text (default) or json output format. * **--no-dev:** Do not show outdated dev dependencies. * **--locked:** Shows updates for packages from the lock file, regardless of what is currently in vendor dir. * **--ignore-platform-reqs:** ignore all platform requirements (`php`, `hhvm`, `lib-*` and `ext-*`) and force the installation even if the local machine does not fulfill these. * **--ignore-platform-req:** ignore a specific platform requirement(`php`, `hhvm`, `lib-*` and `ext-*`) and force the installation even if the local machine does not fulfill it. Multiple requirements can be ignored via wildcard. ## browse / home The `browse` (aliased to `home`) opens a package's repository URL or homepage in your browser. ### Options * **--homepage (-H):** Open the homepage instead of the repository URL. * **--show (-s):** Only show the homepage or repository URL. ## suggests Lists all packages suggested by the currently installed set of packages. You can optionally pass one or multiple package names in the format of `vendor/package` to limit output to suggestions made by those packages only. Use the `--by-package` (default) or `--by-suggestion` flags to group the output by the package offering the suggestions or the suggested packages respectively. If you only want a list of suggested package names, use `--list`. ### Options * **--by-package:** Groups output by suggesting package (default). * **--by-suggestion:** Groups output by suggested package. * **--all:** Show suggestions from all dependencies, including transitive ones (by default only direct dependencies' suggestions are shown). * **--list:** Show only list of suggested package names. * **--no-dev:** Excludes suggestions from `require-dev` packages. ## fund Discover how to help fund the maintenance of your dependencies. This lists all funding links from the installed dependencies. Use `--format=json` to get machine-readable output. ### Options * **--format (-f):** Lets you pick between text (default) or json output format. ## depends / why The `depends` command tells you which other packages depend on a certain package. As with installation `require-dev` relationships are only considered for the root package. ```shell php composer.phar depends doctrine/lexer ``` ```text doctrine/annotations 1.13.3 requires doctrine/lexer (1.*) doctrine/common 2.13.3 requires doctrine/lexer (^1.0) ``` You can optionally specify a version constraint after the package to limit the search. Add the `--tree` or `-t` flag to show a recursive tree of why the package is depended upon, for example: ```shell php composer.phar depends psr/log -t ``` ```text psr/log 1.1.4 Common interface for logging libraries ├──composer/composer 2.4.x-dev (requires psr/log ^1.0 || ^2.0 || ^3.0) ├──composer/composer dev-main (requires psr/log ^1.0 || ^2.0 || ^3.0) ├──composer/xdebug-handler 3.0.3 (requires psr/log ^1 || ^2 || ^3) │ ├──composer/composer 2.4.x-dev (requires composer/xdebug-handler ^2.0.2 || ^3.0.3) │ └──composer/composer dev-main (requires composer/xdebug-handler ^2.0.2 || ^3.0.3) └──symfony/console v5.4.11 (conflicts psr/log >=3) (circular dependency aborted here) ``` ### Options * **--recursive (-r):** Recursively resolves up to the root package. * **--tree (-t):** Prints the results as a nested tree, implies -r. * **--locked:** Read dependency information from `composer.lock` instead of the installed packages. ## prohibits / why-not The `prohibits` command tells you which packages are blocking a given package from being installed. Specify a version constraint to verify whether upgrades can be performed in your project, and if not why not. See the following example: ```shell php composer.phar prohibits symfony/symfony 3.1 ``` ```text laravel/framework v5.2.16 requires symfony/var-dumper (2.8.*|3.0.*) ``` Note that you can also specify platform requirements, for example to check whether you can upgrade your server to PHP 8.0: ```shell php composer.phar prohibits php 8 ``` ```text doctrine/cache v1.6.0 requires php (~5.5|~7.0) doctrine/common v2.6.1 requires php (~5.5|~7.0) doctrine/instantiator 1.0.5 requires php (>=5.3,<8.0-DEV) ``` As with `depends` you can request a recursive lookup, which will list all packages depending on the packages that cause the conflict. ### Options * **--recursive (-r):** Recursively resolves up to the root package. * **--tree (-t):** Prints the results as a nested tree, implies -r. * **--locked:** Read dependency information from `composer.lock` instead of the installed packages. ## validate You should always run the `validate` command before you commit your `composer.json` and `composer.lock` files, and before you tag a release. It will check if your `composer.json` is valid. If a `composer.lock` exists, it will also check if it is up to date with the `composer.json`. ```shell php composer.phar validate ``` ### Options * **--no-check-all:** Do not emit a warning if requirements in `composer.json` use unbound or overly strict version constraints. * **--no-check-lock:** Do not emit an error if `composer.lock` exists and is not up to date. * **--check-lock** Check if lock file is up to date (even when [config.lock](https://getcomposer.org/doc/06-config.md.md#lock) is false) * **--no-check-publish:** Do not emit an error if `composer.json` is unsuitable for publishing as a package on Packagist but is otherwise valid. * **--no-check-version:** Do not emit an error if the version field is present. * **--with-dependencies:** Also validate the composer.json of all installed dependencies. * **--strict:** Return a non-zero exit code for warnings as well as errors. ## status If you often need to modify the code of your dependencies and they are installed from source, the `status` command allows you to check if you have local changes in any of them. ```shell php composer.phar status ``` With the `--verbose` option you get some more information about what was changed: ```shell php composer.phar status -v ``` ```text You have changes in the following dependencies: vendor/seld/jsonlint: M README.mdown ``` ## self-update / selfupdate To update Composer itself to the latest version, run the `self-update` command. It will replace your `composer.phar` with the latest version. ```shell php composer.phar self-update ``` If you would like to instead update to a specific release specify it: ```shell php composer.phar self-update 2.4.0-RC1 ``` If you have installed Composer for your entire system (see [global installation](https://getcomposer.org/doc/00-intro.md.md#globally)), you may have to run the command with `root` privileges ```shell sudo -H composer self-update ``` If Composer was not installed as a PHAR, this command is not available. (This is sometimes the case when Composer was installed by an operating system package manager.) When updating, Composer warns you if the version you are on or updating to is end of life, or is an older line nearing end of life that only receives critical security fixes, and points you to the latest stable release. If a newer Composer version exists but requires a newer PHP version than the one you are running, Composer tells you which PHP version you would need and that you are pinned to an older release line. Backups created for `--rollback` are stored in the [`data-dir`](https://getcomposer.org/doc/06-config.md.md#data-dir), and the public keys used to verify downloads are stored in `COMPOSER_HOME`. Both directories must be writable only by the user that owns the Composer installation and should be treated as trusted: a directory writable by other users could be used to plant a malicious `composer.phar` that a privileged `self-update --rollback` would then install. When rolling back to a tagged release the backup is verified against the published signature from getcomposer.org before being installed (the rollback aborts on a mismatch or if the signature cannot be downloaded); snapshot/dev builds cannot be verified this way, so a rollback to one asks for confirmation when run interactively. ### Options * **--rollback (-r):** Rollback to the last version you had installed. * **--clean-backups:** Delete old backups during an update. This makes the current version of Composer the only backup available after the update. * **--no-progress:** Do not output download progress. * **--update-keys:** Prompt user for a key update. * **--stable:** Force an update to the stable channel. * **--preview:** Force an update to the preview channel. * **--snapshot:** Force an update to the snapshot channel. * **--1:** Force an update to the stable channel, but only use 1.x versions * **--2:** Force an update to the stable channel, but only use 2.x versions * **--set-channel-only:** Only store the channel as the default one and then exit ## config The `config` command allows you to edit Composer config settings and repositories in either the local `composer.json` file or the global `config.json` file. Additionally it lets you edit most properties in the local `composer.json`. ```shell php composer.phar config --list ``` ### Usage `config [options] [setting-key] [setting-value1] ... [setting-valueN]` `setting-key` is a configuration option name and `setting-value1` is a configuration value. For settings that can take an array of values (like `github-protocols`), multiple setting-value arguments are allowed. You can also edit the values of the following properties: `description`, `homepage`, `keywords`, `license`, `minimum-stability`, `name`, `prefer-stable`, `type` and `version`. See the [Config](https://getcomposer.org/doc/06-config.md.md) chapter for valid configuration options. ### Options * **--global (-g):** Operate on the global config file located at `$COMPOSER_HOME/config.json` by default. Without this option, this command affects the local composer.json file or a file specified by `--file`. * **--editor (-e):** Open the local composer.json file using in a text editor as defined by the `EDITOR` env variable. With the `--global` option, this opens the global config file. * **--auth (-a):** Affect auth config file (only used for --editor). * **--unset:** Remove the configuration element named by `setting-key`. * **--list (-l):** Show the list of current config variables. With the `--global` option this lists the global configuration only. * **--file="..." (-f):** Operate on a specific file instead of composer.json. Note that this cannot be used in conjunction with the `--global` option. * **--absolute:** Returns absolute paths when fetching `*-dir` config values instead of relative. * **--json:** JSON decode the setting value. Only supported for `extra.*`, `policy.*.ignore`, `policy.advisories.ignore-id`, `policy.ignore-unreachable`, `audit.ignore` and `audit.ignore-abandoned` keys, it is ignored for all other keys. * **--merge:** Merge the setting value with the current value instead of replacing it. Only supported for `extra.*` keys in combination with `--json`, and for `policy.*.ignore`, `policy.advisories.ignore-id`, `audit.ignore` and `audit.ignore-abandoned` keys with or without `--json`. It is ignored for all other keys. * **--append:** When adding a repository, append it (lowest priority) to the existing ones instead of prepending it (highest priority). * **--source:** Display where the config value is loaded from. ### Modifying Repositories In addition to modifying the config section, the `config` command also supports making changes to the repositories section by using it the following way: ```shell php composer.phar config repositories.foo vcs https://github.com/foo/bar ``` If your repository requires more configuration options, you can instead pass its JSON representation : ```shell php composer.phar config repositories.foo '{"type": "vcs", "url": "http://svn.example.org/my-project/", "trunk-path": "master"}' ``` ### Modifying Extra Values In addition to modifying the config section, the `config` command also supports making changes to the extra section by using it the following way: ```shell php composer.phar config extra.foo.bar value ``` The dots indicate array nesting, a max depth of 3 levels is allowed though. The above would set `"extra": { "foo": { "bar": "value" } }`. If you have a complex value to add/modify, you can use the `--json` and `--merge` flags to edit extra fields as json: ```shell php composer.phar config --json extra.foo.bar '{"baz": true, "qux": []}' ``` ## repository / repo The `repo` command lets you manage repositories in your `composer.json`. It is more powerful and recommended over using `composer config repositories.*` to manipulate the repositories configuration. Refer to [Repositories](https://getcomposer.org/doc/05-repositories.md.md) documentation for details on the available types and configuration options. ### Usage ```shell repo [options] list repo [options] add [repo-name] [repo-type] [url] repo [options] add [repo-name] [json-repo-definition] repo [options] remove [repo-name] repo [options] set-url [repo-name] [url] repo [options] get-url [repo-name] repo [options] enable packagist.org repo [options] disable packagist.org ``` ### Options - **--global (-g):** to modify the global `$COMPOSER_HOME/config.json`. - **--file (-f):** to modify a specific file instead of composer.json. - **--append:** to add a repository with lower priority (by default repositories are prepended and have thus higher priority than existing ones). - **--before [name]:** to insert the new repository before an existing repository named `[name]`. - **--after [name]:** to insert the new repository after an existing repository named `[name]`. The `[name]` must match an existing repository name. ### Examples ```shell php composer.phar repo list php composer.phar repo add foo vcs https://github.com/acme/foo php composer.phar repo add bar composer https://repo.packagist.com/bar php composer.phar repo add zips '{"type":"artifact","url":"/path/to/dir/with/zips"}' php composer.phar repo add baz vcs https://example.org --before foo php composer.phar repo add qux vcs https://example.org --after bar php composer.phar repo remove foo php composer.phar repo set-url foo https://git.example.org/acme/foo php composer.phar repo get-url foo php composer.phar repo disable packagist.org php composer.phar repo enable packagist.org ``` ## policy The `policy` command lets you manage custom dependency policies and their sources in your `composer.json` under `config.policy`. A source points Composer at a remote URL which provides the set of package versions the policy applies to. Adding a source for a dependency policy that does not yet exist will create the policy automatically. Built-in dependency policies (`advisories`, `malware`, `abandoned`) do not accept sources and are rejected. To change their settings, use `composer config policy..` instead — see the [policy](https://getcomposer.org/doc/06-config.md.md#policy) config documentation. ### Usage ```shell policy [options] add-source [policy-name] [source-type] [url] policy [options] add-source [policy-name] [json-source-definition] ``` Currently only `url` is supported as `source-type`, and URLs must start with `https://`. ### Options - **--global (-g):** to modify the global `$COMPOSER_HOME/config.json`. - **--file (-f):** to modify a specific file instead of composer.json. ### Examples ```shell php composer.phar policy add-source my-list url https://example.org/list.json php composer.phar policy add-source my-list '{"type":"url","url":"https://example.org/list.json"}' ``` ## create-project You can use Composer to create new projects from an existing package. This is the equivalent of doing a git clone/svn checkout followed by a `composer install` of the vendors. There are several applications for this: 1. You can deploy application packages. 2. You can check out any package and start developing on patches for example. 3. Projects with multiple developers can use this feature to bootstrap the initial application for development. To create a new project using Composer you can use the `create-project` command. Pass it a package name, and the directory to create the project in. You can also provide a version as a third argument, otherwise the latest version is used. If the directory does not currently exist, it will be created during installation. ```shell php composer.phar create-project composer/hello-world my-project ``` It is also possible to run the command without params in a directory with an existing `composer.json` file to bootstrap a project. By default the command checks for the packages on packagist.org. ### Options * **--stability (-s):** Minimum stability of package. Defaults to `stable`. * **--prefer-install:** There are two ways of downloading a package: `source` and `dist`. Composer uses `dist` by default. If you pass `--prefer-install=source` (or `--prefer-source`) Composer will install from `source` if there is one. This is useful if you want to make a bugfix to a project and get a local git clone of the dependency directly. To get the legacy behavior where Composer use `source` automatically for dev versions of packages, use `--prefer-install=auto`. See also [config.preferred-install](https://getcomposer.org/doc/06-config.md.md#preferred-install). Passing this flag will override the config value. * **--repository:** Provide a custom repository to search for the package, which will be used instead of packagist. Can be either an HTTP URL pointing to a `composer` repository, a path to a local `packages.json` file, or a JSON string which similar to what the [repositories](https://getcomposer.org/doc/04-schema.md.md#repositories-root-only) key accepts. You can use this multiple times to configure multiple repositories. * **--add-repository:** Add the custom repository in the composer.json. If a lock file is present, it will be deleted and an update will be run instead of an install. * **--dev:** Install packages listed in `require-dev`. * **--no-dev:** Disables installation of require-dev packages. * **--no-scripts:** Disables the execution of the scripts defined in the root package. * **--no-progress:** Removes the progress display that can mess with some terminals or scripts which don't handle backspace characters. * **--no-secure-http:** Disable the secure-http config option temporarily while installing the root package. Use at your own risk. Using this flag is a bad idea. * **--keep-vcs:** Skip the deletion of the VCS metadata for the created project. This is mostly useful if you run the command in non-interactive mode. * **--remove-vcs:** Force-remove the VCS metadata without prompting. * **--no-install:** Disables installation of the vendors. * **--no-audit:** Does not run the audit steps after installation is complete. Also see [COMPOSER_NO_AUDIT](https://getcomposer.org/doc/03-cli.md.md#composer_no_audit). * **--audit-format:** Audit output format. Must be "table", "plain", "json", or "summary" (default). * **--no-security-blocking:** DEPRECATED, use `--no-blocking` instead. Allows installing packages with security advisories, that are abandoned or that are still in the cooldown period. Also see [COMPOSER_NO_SECURITY_BLOCKING](https://getcomposer.org/doc/03-cli.md.md#composer_no_security_blocking). * **--no-blocking:** Disables all policy blocking during this command, including the cooldown period. Also see [COMPOSER_NO_BLOCKING](https://getcomposer.org/doc/03-cli.md.md#composer_no_blocking). * **--no-cooldown:** Disables the [cooldown policy](https://getcomposer.org/doc/06-config.md.md#cooldown) blocking during this command, other policies still apply. * **--ignore-platform-reqs:** ignore all platform requirements (`php`, `hhvm`, `lib-*` and `ext-*`) and force the installation even if the local machine does not fulfill these. See also the [`platform`](https://getcomposer.org/doc/06-config.md.md#platform) config option. * **--ignore-platform-req:** ignore a specific platform requirement(`php`, `hhvm`, `lib-*` and `ext-*`) and force the installation even if the local machine does not fulfill it. Multiple requirements can be ignored via wildcard. * **--require:** Require additional package(s) to be added to composer.json after installing the project. If a lock file is present it will be deleted and an update will be run instead of install. Can be specified multiple times for multiple packages. Should be in format `foo/bar:1.0.0` format if you want to specify a constraint. * **--ask:** Ask the user to provide a target directory for the new project. ## dump-autoload / dumpautoload If you need to update the autoloader because of new classes in a classmap package for example, you can use `dump-autoload` to do that without having to go through an install or update. Additionally, it can dump an optimized autoloader that converts PSR-0/4 packages into classmap ones for performance reasons. In large applications with many classes, the autoloader can take up a substantial portion of every request's time. Using classmaps for everything is less convenient in development, but using this option you can still use PSR-0/4 for convenience and classmaps for performance. ### Options * **--optimize (-o):** Convert PSR-0/4 autoloading to classmap to get a faster autoloader. This is recommended especially for production, but can take a bit of time to run, so it is currently not done by default. * **--classmap-authoritative (-a):** Autoload classes from the classmap only. Implicitly enables `--optimize`. * **--apcu:** Use APCu to cache found/not-found classes. * **--apcu-prefix:** Use a custom prefix for the APCu autoloader cache. Implicitly enables `--apcu`. * **--dry-run:** Outputs the operations but will not execute anything. * **--no-dev:** Disables autoload-dev rules. Composer will by default infer this automatically according to the last `install` or `update` `--no-dev` state. * **--dev:** Enables autoload-dev rules. Composer will by default infer this automatically according to the last `install` or `update` `--no-dev` state. * **--ignore-platform-reqs:** ignore all `php`, `hhvm`, `lib-*` and `ext-*` requirements and skip the [platform check](https://getcomposer.org/doc/07-runtime.md.md#platform-check) for these. See also the [`platform`](https://getcomposer.org/doc/06-config.md.md#platform) config option. * **--ignore-platform-req:** ignore a specific platform requirement (`php`, `hhvm`, `lib-*` and `ext-*`) and skip the [platform check](https://getcomposer.org/doc/07-runtime.md.md#platform-check) for it. Multiple requirements can be ignored via wildcard. * **--strict-psr:** Return a failed exit code (1) if PSR-4 or PSR-0 mapping errors are present in the current project (dependencies excluded). Requires `--optimize` to work. * **--strict-ambiguous:** Return a failed exit code (2) if the same class is found in multiple files. It also checks if files or folders exist with different case variants that cause issues on case-insensitive filesystems. Requires `--optimize` to work. ## clear-cache / clearcache / cc Deletes all content from Composer's cache directories. ### Options * **--gc:** Only run garbage collection, not a full cache clear ## licenses Lists the name, version and license of every package installed. Use `--format=json` to get machine-readable output. ### Options * **--locked:** List licenses from the lock file, regardless of what is currently in vendor dir. * **--format:** Format of the output: text, json or summary (default: "text"). * **--no-dev:** Remove dev dependencies from the output. ## run-script / run To run [scripts](https://getcomposer.org/doc/articles/scripts.md.md) manually you can use this command, give it the script name and optionally any required arguments. ### Options * **--timeout:** Set the script timeout in seconds, or 0 for no timeout. * **--dev:** Sets the dev mode. * **--no-dev:** Disable dev mode. * **--list (-l):** List user defined scripts. ## exec Executes a vendored binary/script. You can execute any command and this will ensure that the Composer bin-dir is pushed on your PATH before the command runs. ### Options * **--list (-l):** List the available Composer binaries. ## diagnose If you think you found a bug, or something is behaving strangely, you might want to run the `diagnose` command to perform automated checks for many common problems. ```shell php composer.phar diagnose ``` ## archive This command is used to generate a zip/tar archive for a given package in a given version. It can also be used to archive your entire project without excluded/ignored files. ```shell php composer.phar archive vendor/package 2.0.21 --format=zip ``` ### Options * **--format (-f):** Format of the resulting archive: tar, tar.gz, tar.bz2 or zip (default: "tar"). * **--dir:** Write the archive to this directory (default: ".") * **--file:** Write the archive with the given file name. * **--ignore-filters:** Don't apply the usual exclude rules, so files marked `export-ignore` in `.gitattributes` or listed in [archive.exclude](https://getcomposer.org/doc/04-schema.md.md#archive) are archived too. ## audit This command is used to audit the packages you have installed against defined dependency policies, such as security advisories. It checks for and lists security vulnerability advisories using the [Packagist.org API](https://packagist.org/apidoc#list-security-advisories) by default or other repositories if specified in the `repositories` section of `composer.json`. The command also detects abandoned packages and packages flagged as malware, or packages matched by other dependency policies. The audit command determines if there are vulnerable, abandoned, malware packages, or packages matched by other dependency policies and returns the following exit codes based on the findings: * `0` No issues; * `1` Found packages matching dependency policies or failed due to missing required packages. ```shell php composer.phar audit ``` ### Options * **--no-dev:** Disables auditing of require-dev packages. * **--direct (-D):** Only audit packages directly required by the root package, skipping transitive dependencies. * **--format (-f):** Audit output format. Must be "table" (default), "plain", "json", or "summary". * **--locked:** Audit packages from the lock file, regardless of what is currently in vendor dir. * **--abandoned:** Behavior on abandoned packages. Must be "ignore", "report", or "fail". See also [config.audit.abandoned](https://getcomposer.org/doc/06-config.md.md#abandoned). Passing this flag will override the config value and the environment variable. * **--ignore-severity:** Ignore advisories of a certain severity level. Can be passed one or more time to ignore multiple severities. * **--ignore-unreachable:** Ignore repositories and dependency policy sources that are unreachable or return a non-200 status code. See also [config.policy.ignore-unreachable](https://getcomposer.org/doc/06-config.md.md#ignore-unreachable). ## help To get more information about a certain command, you can use `help`. ```shell php composer.phar help install ``` ## Command-line completion Command-line completion can be enabled by running the `composer completion --help` command and following the instructions. ## Environment variables You can set a number of environment variables that override certain settings. Whenever possible it is recommended to specify these settings in the `config` section of `composer.json` instead. It is worth noting that the env vars will always take precedence over the values specified in `composer.json`. ### COMPOSER By setting the `COMPOSER` env variable it is possible to set the filename of `composer.json` to something else. For example: ```shell COMPOSER=composer-other.json php composer.phar install ``` The generated lock file will use the same name: `composer-other.lock` in this example. ### COMPOSER_ALLOW_SUPERUSER If set to 1, this env disables the warning about running commands as root/super user. It also disables automatic clearing of sudo sessions, so you should really only set this if you use Composer as a super user at all times like in docker containers. ### COMPOSER_ALLOW_UNSAFE_PHAR_METADATA This env var only has an effect on PHP versions before 8.0. On those versions Composer refuses to read or extract `tar`/`phar` dist archives, because parsing such an archive is not safe to do with untrusted input on PHP < 8.0. The recommended fix is to upgrade to PHP 8.0 or newer. If you cannot upgrade and accept the risk, set this to 1 to allow Composer to process these archives anyway. PHP 8.0+ is unaffected and ignores this setting. ### COMPOSER_ALLOW_XDEBUG If set to 1, this env allows running Composer when the Xdebug extension is enabled, without restarting PHP without it. ### COMPOSER_AUTH The `COMPOSER_AUTH` var allows you to set up authentication as an environment variable. The contents of the variable should be a JSON formatted object containing [http-basic, github-oauth, bitbucket-oauth, ... objects as needed](https://getcomposer.org/doc/articles/authentication-for-private-packages.md.md), and following the [spec from the config](https://getcomposer.org/doc/06-config.md.md). Any other config setting found in there is ignored, except for `github-domains`, `gitlab-domains` and `forgejo-domains`. The same applies to a project's `auth.json` file. ### COMPOSER_BIN_COMPAT Override the [`bin-compat`](https://getcomposer.org/doc/06-config.md.md#bin-compat) config setting. ### COMPOSER_BIN_DIR By setting this option you can change the `bin` ([Vendor Binaries](https://getcomposer.org/doc/articles/vendor-binaries.md.md)) directory to something other than `vendor/bin`. ### COMPOSER_CACHE_DIR The `COMPOSER_CACHE_DIR` var allows you to change the Composer cache directory, which is also configurable via the [`cache-dir`](https://getcomposer.org/doc/06-config.md.md#cache-dir) option. By default, it points to `C:\Users\\AppData\Local\Composer` (or `%LOCALAPPDATA%/Composer`) on Windows. On \*nix systems that follow the [XDG Base Directory Specifications](https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html), it points to `$XDG_CACHE_HOME/composer`. On other \*nix systems and on macOS, it points to `$COMPOSER_HOME/cache`. See [Caching Composer dependencies](https://getcomposer.org/doc/articles/caching.md.md) for how to cache it in CI and container builds. ### COMPOSER_CAFILE By setting this environmental value, you can set a path to a certificate bundle file to be used during SSL/TLS peer verification. ### COMPOSER_DISABLE_XDEBUG_WARN If set to 1, this env suppresses a warning when Composer is running with the Xdebug extension enabled. ### COMPOSER_DISCARD_CHANGES This env var controls the [`discard-changes`](https://getcomposer.org/doc/06-config.md.md#discard-changes) config option. ### COMPOSER_FUND If set to 0, this env suppresses funding notices when installing. ### COMPOSER_HOME The `COMPOSER_HOME` var allows you to change the Composer home directory. This is a hidden, global (per-user on the machine) directory that is shared between all projects. Use `composer config --global home` to see the location of the home directory. By default, it points to `C:\Users\\AppData\Roaming\Composer` on Windows and `/Users//.composer` on macOS. On \*nix systems that follow the [XDG Base Directory Specifications](https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html), it points to `$XDG_CONFIG_HOME/composer`. On other \*nix systems, it points to `/home//.composer`. This directory holds the public keys used to verify Composer downloads during `self-update`, so it must be writable only by the user that owns the Composer installation and should be treated as a trusted location. #### COMPOSER_HOME/config.json You may put a `config.json` file into the location which `COMPOSER_HOME` points to. Composer will partially (only `config` and `repositories` keys) merge this configuration with your project's `composer.json` when you run the `install` and `update` commands. This file allows you to set [repositories](https://getcomposer.org/doc/05-repositories.md.md) and [configuration](https://getcomposer.org/doc/06-config.md.md) for the user's projects. In case global configuration matches _local_ configuration, the _local_ configuration in the project's `composer.json` always wins. ### COMPOSER_HTACCESS_PROTECT Defaults to `1`. If set to `0`, Composer will not create `.htaccess` files in the Composer home, cache, and data directories. ### COMPOSER_MEMORY_LIMIT If set, the value is used as php's memory_limit. ### COMPOSER_MIRROR_PATH_REPOS If set to 1, this env changes the default path repository strategy to `mirror` instead of `symlink`. As it is the default strategy being set it can still be overwritten by repository options. ### COMPOSER_NO_INTERACTION If set to 1, this env var will make Composer behave as if you passed the `--no-interaction` flag to every command. This can be set on build boxes/CI. ### COMPOSER_PROCESS_TIMEOUT This env var controls the time Composer waits for commands (such as git commands) to finish executing. The default value is 300 seconds (5 minutes). ### COMPOSER_ROOT_VERSION By setting this var you can specify the version of the root package, if it cannot be guessed from VCS info and is not present in `composer.json`. ### COMPOSER_VENDOR_DIR By setting this var you can make Composer install the dependencies into a directory other than `vendor`. ### COMPOSER_RUNTIME_ENV This lets you hint under which environment Composer is running, which can help Composer work around some environment specific issues. The only value currently supported is `virtualbox`, which then enables some short `sleep()` calls to wait for the filesystem to have written files properly before we attempt reading them. You can set the environment variable if you use Vagrant or VirtualBox and experience issues with files not being found during installation even though they should be present. ### http_proxy or HTTP_PROXY ### HTTP_PROXY_REQUEST_FULLURI ### HTTPS_PROXY_REQUEST_FULLURI ### no_proxy or NO_PROXY See the [proxy documentation](https://getcomposer.org/doc/faqs/how-to-use-composer-behind-a-proxy.md.md) for more details on how to use proxy env vars. ### COMPOSER_MAX_PARALLEL_HTTP Set to an integer to configure how many files can be downloaded in parallel. This defaults to 12 and must be between 1 and 50. If your proxy has issues with concurrency maybe you want to lower this. Increasing it should generally not result in performance gains. ### COMPOSER_MAX_PARALLEL_PROCESSES Set to an integer to configure how many processes can be executed in parallel. This defaults to 10 and must be between 1 and 50. ### COMPOSER_IPRESOLVE Set to `4` or `6` to force IPv4 or IPv6 DNS resolution. This only works when the curl extension is used for downloads. ### COMPOSER_SELF_UPDATE_TARGET If set, makes the self-update command write the new Composer phar file into that path instead of overwriting itself. Useful for updating Composer on a read-only filesystem. ### COMPOSER_DISABLE_NETWORK If set to `1`, disables network access (best effort). This can be used for debugging or to run Composer on a plane or a starship with poor connectivity. If set to `prime`, GitHub VCS repositories will prime the cache, so it can then be used fully offline with `1`. ### COMPOSER_DEBUG_EVENTS If set to `1`, outputs information about events being dispatched, which can be useful for plugin authors to identify what is firing when exactly. ### COMPOSER_SKIP_SCRIPTS Accepts a comma-separated list of event names, e.g. `post-install-cmd` for which scripts execution should be skipped. ### COMPOSER_NO_AUDIT If set to `1`, it is the equivalent of passing the `--no-audit` option to a `require`, `update`, `remove` or `create-project` command. ### COMPOSER_AUDIT_ABANDONED Set to `ignore`, `report` or `fail` to override the [policy.abandoned.audit](https://getcomposer.org/doc/06-config.md.md#audit) config option. Has no effect when `policy.abandoned` is set to `false` in composer.json. ### COMPOSER_POLICY Main dependency policy switch. Set to `0` to disable all dependency policy enforcement on updates, installs and audits, or `1` to enable it. Setting this to `1` will use the policy configuration in the composer.json. If you want to change the config value, use `composer config policy 1` instead. When set to `0`, all policy specific overrides below are ignored — the whole dependency policy config is short-circuited to disabled. ### COMPOSER_NO_BLOCKING If set to `1`, it is the equivalent of passing the `--no-blocking` option to a `require`, `update`, `remove`, `install`, or `create-project` command. This disables all policy based blocking of dependencies, including the cooldown period. It overrides the `block` config option for each configured dependency policy e.g. [policy.advisories.block](https://getcomposer.org/doc/06-config.md.md#block). ### COMPOSER_NO_SECURITY_BLOCKING DEPRECATED, use [COMPOSER_NO_BLOCKING](https://getcomposer.org/doc/03-cli.md.md#composer_no_blocking) instead. If set to `1`, it is the equivalent of passing the `--no-security-blocking` option to a `require`, `update`, `remove`, `install`, or `create-project` command. This allows installing packages with security advisories, that are abandoned or that are still in the cooldown period. It overrides the config option [policy.advisories.block](https://getcomposer.org/doc/06-config.md.md#block). ### COMPOSER_POLICY_ADVISORIES_BLOCK If set to `1`, enables blocking of packages with security advisories during dependency resolution (equivalent to setting `policy.advisories.block` to `true`). If set to `0`, disables blocking. ### COMPOSER_POLICY_MALWARE_BLOCK If set to `1`, enables blocking of packages flagged as malware during dependency resolution (equivalent to setting `policy.malware.block` to `true`). If set to `0`, disables blocking. ### COMPOSER_POLICY_ABANDONED_BLOCK If set to `1`, enables blocking of abandoned packages during dependency resolution (equivalent to setting `policy.abandoned.block` to `true`). If set to `0`, disables blocking. Value takes precedence over the value of the legacy variable [COMPOSER_SECURITY_BLOCKING_ABANDONED](https://getcomposer.org/doc/03-cli.md.md#composer_security_blocking_abandoned) when it's set to a different value. ### COMPOSER_SECURITY_BLOCKING_ABANDONED DEPRECATED, use [COMPOSER_POLICY_ABANDONED_BLOCK](https://getcomposer.org/doc/03-cli.md.md#composer_policy_abandoned_block) instead. If set to `1`, enables blocking of abandoned packages during dependency resolution (equivalent to setting `audit.block-abandoned` config to `true`). If set to `0`, disables blocking of abandoned packages. It overrides the config option [audit.block-abandoned](https://getcomposer.org/doc/06-config.md.md#block-abandoned). ### COMPOSER_POLICY_COOLDOWN_PERIOD If set to a value accepted by [policy.cooldown.period](https://getcomposer.org/doc/06-config.md.md#period), such as `"7 days"`, `"24 hours"` or an integer number of seconds, enables the cooldown policy. Package versions published within that period are withheld during `composer update`/`require`. Set to `0` to disable. This overrides only the `period` value from [policy.cooldown](https://getcomposer.org/doc/06-config.md.md#cooldown); any `ignore` rules configured in composer.json are still respected. ### COMPOSER_POLICY_COOLDOWN_BLOCK If set to `1`, forces cooldown blocking on; if set to `0`, disables it. Overrides the [policy.cooldown.block](https://getcomposer.org/doc/06-config.md.md#block-3) config option. ### COMPOSER_NO_DEV If set to `1`, it is the equivalent of passing the `--update-no-dev` option to `require` or the `--no-dev` option to `install` or `update`. You can override this for a single command by setting `COMPOSER_NO_DEV=0`. ### COMPOSER_PREFER_STABLE If set to `1`, it is the equivalent of passing the `--prefer-stable` option to `update` or `require`. ### COMPOSER_PREFER_LOWEST If set to `1`, it is the equivalent of passing the `--prefer-lowest` option to `update` or `require`. ### COMPOSER_PREFER_DEV_OVER_PRERELEASE If set to `1`, when resolving dependencies with both `--prefer-stable` and `--prefer-lowest` enabled, dev versions are treated as more stable than alpha/beta/RC versions in cases where no stable release exists. This is useful to test lowest versions while still preferring branches that may contain critical fixes over prerelease versions. ### COMPOSER_MINIMAL_CHANGES If set to `1`, it is the equivalent of passing the `--minimal-changes` option to `update`, `require` or `remove`. ### COMPOSER_IGNORE_PLATFORM_REQ or COMPOSER_IGNORE_PLATFORM_REQS If `COMPOSER_IGNORE_PLATFORM_REQS` set to `1`, it is the equivalent of passing the `--ignore-platform-reqs` argument. Otherwise, specifying a comma separated list in `COMPOSER_IGNORE_PLATFORM_REQ` will ignore those specific requirements. For example, if a development workstation will never run database queries, this can be used to ignore the requirement for the database extensions to be available. If you set `COMPOSER_IGNORE_PLATFORM_REQ=ext-oci8`, then composer will allow packages to be installed even if the `oci8` PHP extension is not enabled. ### COMPOSER_WITH_DEPENDENCIES If set to `1`, it is the equivalent of passing the `--with-dependencies` option to `update`, `require` or `remove`. ### COMPOSER_WITH_ALL_DEPENDENCIES If set to `1`, it is the equivalent of passing the `--with-all-dependencies` option to `update`, `require` or `remove`. ### COMPOSER_TERMINAL_STATUS Controls terminal status reports. Defaults to `auto`. - `auto` sends OSC 7501 status reports and also sends OSC 9 progress reports when the environment identifies Windows Terminal (`WT_SESSION`), ConEmu (`ConEmuANSI=ON`), Ghostty 1.2.0 or newer, or iTerm2 3.6.6 or newer. Ghostty and iTerm2 are identified by `TERM_PROGRAM` and `TERM_PROGRAM_VERSION`. Unknown terminals receive only OSC 7501. Through SSH, tmux, or screen, automatic selection also sends only OSC 7501 because the outer terminal's identity does not establish support along the connection. - `off` disables status reports. - `7501` selects only OSC 7501. - `9;4` selects only OSC 9 progress reports. - `7501,9;4` selects both protocols, including in environments where automatic selection cannot recognize support. - Any other value, such as `0` or `false`, disables status reports. Unknown entries in a comma-separated list are ignored. Protocol selection is resolved once for each console IO instance. All modes respect quiet output, disabled ANSI decoration, and redirected stderr. Forcing ANSI with `--ansi` does not enable reports on redirected streams. OSC 7501 is sent without querying the terminal. Supporting terminals can show Composer's state, messages, and reasons for waiting. Terminals that do not recognize this protocol are expected to ignore it. OSC 9 progress reports carry progress, paused, and error states. Completion or cancellation clears their progress indicator. Ghostty hides the indicator after 15 seconds without an update. Commands using a progress bar should aim to report progress less than 15 seconds apart to keep it visible. Older terminals may interpret OSC 9 as a desktop notification, so explicitly selecting `9;4` requires a compatible terminal. For example, in a POSIX shell: ```sh COMPOSER_TERMINAL_STATUS=off composer install COMPOSER_TERMINAL_STATUS='7501,9;4' composer update ``` ### SHELL_VERBOSITY Since Composer uses [symfony/console](https://github.com/symfony/console), you can define the [verbosity level](https://symfony.com/doc/current/console/verbosity.html). `SHELL_VERBOSITY=-1` to hide the output of Composer (this is equivalent to using the CLI option `--quiet`). Please note that this will apply to every tool that rely on `symfony/console`, you can set `SHELL_VERBOSITY=0` after the calls to Composer in order to restore the default verbosity level. ← [Libraries](https://getcomposer.org/doc/02-libraries.md.md) | [Schema](https://getcomposer.org/doc/04-schema.md.md) → --- Source: https://getcomposer.org/doc/04-schema.md # The composer.json schema This chapter will explain all of the fields available in `composer.json`. ## JSON schema We have a [JSON schema](https://json-schema.org) that documents the format and can also be used to validate your `composer.json`. In fact, it is used by the `validate` command. You can find it at: https://getcomposer.org/schema.json ## Root Package The root package is the package defined by the `composer.json` at the root of your project. It is the main `composer.json` that defines your project requirements. Certain fields only apply when in the root package context. One example of this is the `config` field. Only the root package can define configuration. The config of dependencies is ignored. This makes the `config` field `root-only`. > **Note:** A package can be the root package or not, depending on the context. > For example, if your project depends on the `monolog` library, your project > is the root package. However, if you clone `monolog` from GitHub in order to > fix a bug in it, then `monolog` is the root package. ## Properties ### name The name of the package. It consists of vendor name and project name, separated by `/`. Examples: * monolog/monolog * igorw/event-source The name must be lowercase and consist of words separated by `-`, `.` or `_`. The complete name should match `^[a-z0-9]([_.-]?[a-z0-9]+)*/[a-z0-9](([_.]|-{1,2})?[a-z0-9]+)*$`. The `name` property is required for published packages (libraries). > **Note:** Before Composer version 2.0, a name could contain any character, including white spaces. ### description A short description of the package. Usually this is one line long. Required for published packages (libraries). ### version The version of the package. In most cases this is not required and should be omitted (see below). This must follow the format of `X.Y.Z` or `vX.Y.Z` with an optional suffix of `-dev`, `-patch` (`-p`), `-alpha` (`-a`), `-beta` (`-b`) or `-RC`. The patch, alpha, beta and RC suffixes can also be followed by a number. Examples: - 1.0.0 - 1.0.2 - 1.1.0 - 0.2.5 - 1.0.0-dev - 1.0.0-alpha3 - 1.0.0-beta2 - 1.0.0-RC5 - v2.0.4-p1 Optional if the package repository can infer the version from somewhere, such as the VCS tag name in the VCS repository. In that case it is also recommended to omit it. > **Note:** Packagist uses VCS repositories, so the statement above is very > much true for Packagist as well. Specifying the version yourself will > most likely end up creating problems at some point due to human error. ### type The type of the package. It defaults to `library`. Package types are used for custom installation logic. If you have a package that needs some special logic, you can define a custom type. This could be a `symfony-bundle`, a `wordpress-plugin` or a `typo3-cms-extension`. These types will all be specific to certain projects, and they will need to provide an installer capable of installing packages of that type. Out of the box, Composer supports four types: - **library:** This is the default. It will copy the files to `vendor`. - **project:** This denotes a project rather than a library. For example application shells like the [Symfony standard edition](https://github.com/symfony/symfony-standard), CMSs like the [Silverstripe installer](https://github.com/silverstripe/silverstripe-installer) or full fledged applications distributed as packages. This can for example be used by IDEs to provide listings of projects to initialize when creating a new workspace. - **metapackage:** An empty package that contains requirements and will trigger their installation, but contains no files and will not write anything to the filesystem. As such, it does not require a dist or source key to be installable. - **composer-plugin:** A package of type `composer-plugin` may provide an installer for other packages that have a custom type. Read more in the [dedicated article](https://getcomposer.org/doc/articles/custom-installers.md.md). - **php-ext** and **php-ext-zend**: These names are reserved for PHP extension packages which are written in C. Do not use these types for packages written in PHP. Only use a custom type if you need custom logic during installation. It is recommended to omit this field and have it default to `library`. ### keywords An array of keywords that the package is related to. These can be used for searching and filtering. Examples: - logging - events - database - redis - templating > **Note**: Some special keywords trigger `composer require` without the > `--dev` option to prompt users if they would like to add these packages to > `require-dev` instead of `require`. These are: `dev`, `testing`, `static analysis`. > **Note**: The range of characters allowed inside the string is restricted to > unicode letters or numbers, space `" "`, dot `.`, underscore `_` and dash `-`. (Regex: `'{^[\p{N}\p{L} ._-]+$}u'`) > Using other characters will emit a warning when running `composer validate` and > will cause the package to fail updating on Packagist.org. Optional. ### homepage A URL to the website of the project. Optional. ### readme A relative path to the readme document. Defaults to `README.md`. This is mainly useful for packages not on GitHub, as for GitHub packages Packagist.org will use the readme API to fetch the one detected by GitHub. Optional. ### time Release date of the version. Must be in `YYYY-MM-DD` or `YYYY-MM-DD HH:MM:SS` format in UTC timezone. Optional. ### license The license of the package. This can be either a string or an array of strings. The recommended notation for the most common licenses is (alphabetical): - Apache-2.0 - BSD-2-Clause - BSD-3-Clause - BSD-4-Clause - GPL-2.0-only / GPL-2.0-or-later - GPL-3.0-only / GPL-3.0-or-later - LGPL-2.1-only / LGPL-2.1-or-later - LGPL-3.0-only / LGPL-3.0-or-later - MIT Optional, but it is highly recommended to supply this. More identifiers are listed at the [SPDX Open Source License Registry](https://spdx.org/licenses/). > **Note:** For closed-source software, you may use `"proprietary"` as the license identifier. An Example: ```json { "license": "MIT" } ``` For a package, when there is a choice between licenses ("disjunctive license"), multiple can be specified as an array. An Example for disjunctive licenses: ```json { "license": [ "LGPL-2.1-only", "GPL-3.0-or-later" ] } ``` Alternatively they can be separated with "or" and enclosed in parentheses; ```json { "license": "(LGPL-2.1-only or GPL-3.0-or-later)" } ``` Similarly, when multiple licenses need to be applied ("conjunctive license"), they should be separated with "and" and enclosed in parentheses. ### authors The authors of the package. This is an array of objects. Each author object can have following properties: * **name:** The author's name. Usually their real name. * **email:** The author's email address. * **homepage:** URL to the author's website. * **role:** The author's role in the project (e.g. developer or translator) An example: ```json { "authors": [ { "name": "Nils Adermann", "email": "naderman@naderman.de", "homepage": "https://www.naderman.de", "role": "Developer" }, { "name": "Jordi Boggiano", "email": "j.boggiano@seld.be", "homepage": "https://seld.be", "role": "Developer" } ] } ``` Optional, but highly recommended. ### support Various information to get support about the project. Support information includes the following: * **email:** Email address for support. * **issues:** URL to the issue tracker. * **forum:** URL to the forum. * **wiki:** URL to the wiki. * **irc:** IRC channel for support, as irc://server/channel. * **source:** URL to browse or download the sources. * **docs:** URL to the documentation. * **rss:** URL to the RSS feed. * **chat:** URL to the chat channel. * **security:** URL to the vulnerability disclosure policy (VDP). An example: ```json { "support": { "email": "support@example.org", "irc": "irc://irc.freenode.org/composer" } } ``` Optional. ### funding A list of URLs to provide funding to the package authors for maintenance and development of new functionality. Each entry consists of the following * **type:** The type of funding, or the platform through which funding can be provided, e.g. patreon, opencollective, tidelift or github. * **url:** URL to a website with details, and a way to fund the package. An example: ```json { "funding": [ { "type": "patreon", "url": "https://www.patreon.com/phpdoctrine" }, { "type": "tidelift", "url": "https://tidelift.com/subscription/pkg/packagist-doctrine_doctrine-bundle" }, { "type": "other", "url": "https://www.doctrine-project.org/sponsorship.html" } ] } ``` Optional. ### source Where the package sources live, used when installing the package from source. `type`, `url` and `reference` are required, `mirrors` is optional. ```json { "source": { "type": "git", "url": "https://github.com/composer/composer.git", "reference": "2.8.0" } } ``` Where `type` is `git`, the reference is a commit id, branch or tag name. Where it is `svn`, it is the reference that gets appended to the URL when running `svn co`. You normally do not write this field yourself. The repository a package comes from provides it: Packagist and other `composer` repositories fill it in from the VCS they read the package from, and a VCS repository fills it in from the branch or tag it is reading. The place you do write it by hand is the definition of a [`package` repository](https://getcomposer.org/doc/05-repositories.md.md#package-1). Optional. ### dist Where the package archive lives, used when installing the package from dist. `type` and `url` are required, `reference`, `shasum` and `mirrors` are optional. ```json { "dist": { "type": "zip", "url": "https://www.smarty.net/files/Smarty-3.1.7.zip" } } ``` The same applies as for [source](https://getcomposer.org/doc/04-schema.md.md#source): this is normally provided by the repository the package comes from, and written by hand only in a [`package` repository](https://getcomposer.org/doc/05-repositories.md.md#package-1). The `url` may contain placeholders, which is what lets one URL serve every version of a package instead of one entry per version. They are expanded when the package is downloaded: | Placeholder | Replaced by | | --- | --- | | `%package%` | the package name, e.g. `acme/lib` | | `%version%` | the normalized version, e.g. `1.2.3.0` | | `%prettyVersion%` | the version defined in the tag or composer.json, e.g. `v1.2.3` | | `%reference%` | the `reference` above | | `%type%` | the `type` above | ```json { "dist": { "type": "zip", "url": "https://example.org/dist/%package%/%prettyVersion%.zip" } } ``` Two of them are hashed rather than inserted as-is, so that they cannot produce a path segment or escape the URL: `%version%` is replaced by its MD5 hash when the version contains a `/`, as `dev-feature/x` does, and `%reference%` by its MD5 hash unless it is already hexadecimal. A branch or tag name given as the reference therefore appears hashed in the URL. Placeholders are expanded in `dist` only. A `source` url is used as it is, since the VCS it names is cloned once and then checked out at the reference. Optional. ### Package links All of the following take an object which maps package names to versions of the package via version constraints. Read more about versions [here](https://getcomposer.org/doc/articles/versions.md.md). Example: ```json { "require": { "monolog/monolog": "1.0.*" } } ``` All links are optional fields. `require` and `require-dev` additionally support _stability flags_ ([root-only](https://getcomposer.org/doc/04-schema.md.md#root-package)). They take the form "_constraint_@_stability flag_". These allow you to further restrict or expand the stability of a package beyond the scope of the [minimum-stability](https://getcomposer.org/doc/04-schema.md.md#minimum-stability-root-only) setting. You can apply them to a constraint, or apply them to an empty _constraint_ if you want to allow unstable packages of a dependency for example. Example: ```json { "require": { "monolog/monolog": "1.0.*@beta", "acme/foo": "@dev" } } ``` If one of your dependencies has a dependency on an unstable package you need to explicitly require it as well, along with its sufficient stability flag. Example: Assuming `doctrine/doctrine-fixtures-bundle` requires `"doctrine/data-fixtures": "dev-master"` then inside the root composer.json you need to add the second line below to allow dev releases for the `doctrine/data-fixtures` package : ```json { "require": { "doctrine/doctrine-fixtures-bundle": "dev-master", "doctrine/data-fixtures": "@dev" } } ``` `require` and `require-dev` additionally support explicit references (i.e. commit) for dev versions to make sure they are locked to a given state, even when you run update. These only work if you explicitly require a dev version and append the reference with `#`. This is also a [root-only](https://getcomposer.org/doc/04-schema.md.md#root-package) feature and will be ignored in dependencies. Example: ```json { "require": { "monolog/monolog": "dev-master#2eb0c0978d290a1c45346a1955188929cb4e5db7", "acme/foo": "1.0.x-dev#abc123" } } ``` > **Note:** This feature has severe technical limitations. The reference only > changes which commit gets checked out; it is applied at install time as a > low-level override that the dependency solver never sees. As a result: > > - The package's `composer.json` metadata (its own `require` entries, autoload > rules, and so on) is read from the branch you name, at its current state, > not from the commit you pinned. The dependencies Composer resolves can > therefore differ from those declared at that commit. > - The override is only reliable for source installs. A dist install can only > honor the reference when the dist is fetched from a source that can build an > archive for an arbitrary commit (e.g. GitHub); otherwise the pinned commit > is ignored when downloading the files. > > You should therefore only use this as a temporary solution during development > to remediate transient issues, until you can switch to tagged releases. The > Composer team does not actively support this feature and will not accept bug > reports related to it. It is also possible to inline-alias a package constraint so that it matches a constraint that it otherwise would not. For more information [see the aliases article](https://getcomposer.org/doc/articles/aliases.md.md). `require` and `require-dev` also support references to specific PHP versions and PHP extensions your project needs to run successfully. Example: ```json { "require": { "php": ">=7.4", "ext-mbstring": "*" } } ``` > **Note:** It is important to list PHP extensions your project requires. > Not all PHP installations are created equal: some may miss extensions you > may consider as standard (such as `ext-mysqli` which is not installed by > default in Fedora/CentOS minimal installation systems). Failure to list > required PHP extensions may lead to a bad user experience: Composer will > install your package without any errors but it will then fail at run-time. > The `composer show --platform` command lists all PHP extensions available on > your system. You may use it to help you compile the list of extensions you > use and require. Alternatively you may use third party tools to analyze > your project for the list of extensions used. #### require Map of packages required by this package. The package will not be installed unless those requirements can be met. #### require-dev ([root-only](https://getcomposer.org/doc/04-schema.md.md#root-package)) Map of packages required for developing this package, or running tests, etc. The dev requirements of the root package are installed by default. Both `install` or `update` support the `--no-dev` option that prevents dev dependencies from being installed. #### conflict Map of packages that are incompatible with this version of this package. They will not be allowed to be installed together with your package. Note that when specifying ranges like `<1.0 >=1.1` in a `conflict` link, this will state a conflict with all versions that are less than 1.0 *and* equal or newer than 1.1 at the same time, which is probably not what you want. You probably want to go for `<1.0 || >=1.1` in this case. #### replace Map of packages that are replaced by this package. This allows you to fork a package, publish it under a different name with its own version numbers, while packages requiring the original package continue to work with your fork because it replaces the original package. This is also useful for packages that contain sub-packages, for example the main symfony/symfony package contains all the Symfony Components which are also available as individual packages. If you require the main package it will automatically fulfill any requirement of one of the individual components, since it replaces them. Caution is advised when using replace for the sub-package purpose explained above. You should then typically only replace using `self.version` as a version constraint, to make sure the main package only replaces the sub-packages of that exact version, and not any other version, which would be incorrect. #### provide Map of packages that are provided by this package. This is mostly useful for implementations of common interfaces. A package could depend on some virtual package e.g. `psr/log-implementation`, any library that implements this logger interface would list it in `provide`. Implementors can then be [found on Packagist.org](https://packagist.org/providers/psr/log-implementation). Using `provide` with the name of an actual package rather than a virtual one implies that the code of that package is also shipped, in which case `replace` is generally a better choice. A common convention for packages providing an interface and relying on other packages to provide an implementation (for instance the PSR interfaces) is to use a `-implementation` suffix for the name of the virtual package corresponding to the interface package. #### suggest Suggested packages that can enhance or work well with this package. These are informational and are displayed after the package is installed, to give your users a hint that they could add more packages, even though they are not strictly required. The format is like package links above, except that the values are free text and not version constraints. Example: ```json { "suggest": { "monolog/monolog": "Allows more advanced logging of the application flow", "ext-xml": "Needed to support XML format in class Foo" } } ``` ### autoload Autoload mapping for a PHP autoloader. [`PSR-4`](https://www.php-fig.org/psr/psr-4/) and [`PSR-0`](http://www.php-fig.org/psr/psr-0/) autoloading, `classmap` generation and `files` includes are supported. PSR-4 is the recommended way since it offers greater ease of use (no need to regenerate the autoloader when you add classes). #### PSR-4 Under the `psr-4` key you define a mapping from namespaces to paths, relative to the package root. When autoloading a class like `Foo\\Bar\\Baz` a namespace prefix `Foo\\` pointing to a directory `src/` means that the autoloader will look for a file named `src/Bar/Baz.php` and include it if present. Note that as opposed to the older PSR-0 style, the prefix (`Foo\\`) is **not** present in the file path. Namespace prefixes must end in `\\` to avoid conflicts between similar prefixes. For example `Foo` would match classes in the `FooBar` namespace so the trailing backslashes solve the problem: `Foo\\` and `FooBar\\` are distinct. The PSR-4 references are all combined, during install/update, into a single key => value array which may be found in the generated file `vendor/composer/autoload_psr4.php`. Example: ```json { "autoload": { "psr-4": { "Monolog\\": "src/", "Vendor\\Namespace\\": "" } } } ``` If you need to search for a same prefix in multiple directories, you can specify them as an array as such: ```json { "autoload": { "psr-4": { "Monolog\\": ["src/", "lib/"] } } } ``` If you want to have a fallback directory where any namespace will be looked for, you can use an empty prefix like: ```json { "autoload": { "psr-4": { "": "src/" } } } ``` #### PSR-0 Under the `psr-0` key you define a mapping from namespaces to paths, relative to the package root. Note that this also supports the PEAR-style non-namespaced convention. Please note namespace declarations should end in `\\` to make sure the autoloader responds exactly. For example `Foo` would match in `FooBar` so the trailing backslashes solve the problem: `Foo\\` and `FooBar\\` are distinct. The PSR-0 references are all combined, during install/update, into a single key => value array which may be found in the generated file `vendor/composer/autoload_namespaces.php`. Example: ```json { "autoload": { "psr-0": { "Monolog\\": "src/", "Vendor\\Namespace\\": "src/", "Vendor_Namespace_": "src/" } } } ``` If you need to search for a same prefix in multiple directories, you can specify them as an array as such: ```json { "autoload": { "psr-0": { "Monolog\\": ["src/", "lib/"] } } } ``` The PSR-0 style is not limited to namespace declarations only but may be specified right down to the class level. This can be useful for libraries with only one class in the global namespace. If the php source file is also located in the root of the package, for example, it may be declared like this: ```json { "autoload": { "psr-0": { "UniqueGlobalClass": "" } } } ``` If you want to have a fallback directory where any namespace can be, you can use an empty prefix like: ```json { "autoload": { "psr-0": { "": "src/" } } } ``` #### Classmap The `classmap` references are all combined, during install/update, into a single key => value array which may be found in the generated file `vendor/composer/autoload_classmap.php`. This map is built by scanning for classes in all `.php` and `.inc` files in the given directories/files. You can use the classmap generation support to define autoloading for all libraries that do not follow PSR-0/4. To configure this you specify all directories or files to search for classes. Example: ```json { "autoload": { "classmap": ["src/", "lib/", "Something.php"] } } ``` Wildcards (`*`) are also supported in a classmap paths, and expand to match any directory name: Example: ```json { "autoload": { "classmap": ["src/addons/*/lib/", "3rd-party/*", "Something.php"] } } ``` #### Files If you want to require certain files explicitly on every request then you can use the `files` autoloading mechanism. This is useful if your package includes PHP functions that cannot be autoloaded by PHP. Example: ```json { "autoload": { "files": ["src/MyLibrary/functions.php"] } } ``` Files autoload rules are included whenever `vendor/autoload.php` is included, right after the autoloader is registered. The order of inclusion depends on package dependencies so that if package A depends on B, files in package B will be included first to ensure package B is fully initialized and ready to be used when files from package A are included. If two packages have the same amount of dependents or no dependencies, the order is alphabetical. Files from the root package are always loaded last, and you cannot use files autoloading yourself to override functions from your dependencies. If you want to achieve that we recommend you include your own functions *before* including Composer's `vendor/autoload.php`. #### Exclude files from classmaps If you want to exclude some files or folders from the classmap you can use the `exclude-from-classmap` property. This might be useful to exclude test classes in your live environment, for example, as those will be skipped from the classmap even when building an optimized autoloader. The classmap generator will ignore all files in the paths configured here. The paths are absolute from the package root directory (i.e. composer.json location), and support `*` to match anything but a slash, and `**` to match anything. `**` is implicitly added to the end of the paths. Example: ```json { "autoload": { "exclude-from-classmap": ["/Tests/", "/test/", "/tests/"] } } ``` #### Optimizing the autoloader The autoloader can have quite a substantial impact on your request time (50-100ms per request in large frameworks using a lot of classes). See the [article about optimizing the autoloader](https://getcomposer.org/doc/articles/autoloader-optimization.md.md) for more details on how to reduce this impact. ### autoload-dev ([root-only](https://getcomposer.org/doc/04-schema.md.md#root-package)) This section allows defining autoload rules for development purposes. Classes needed to run the test suite should not be included in the main autoload rules to avoid polluting the autoloader in production and when other people use your package as a dependency. Therefore, it is a good idea to rely on a dedicated path for your unit tests and to add it within the autoload-dev section. Example: ```json { "autoload": { "psr-4": { "MyLibrary\\": "src/" } }, "autoload-dev": { "psr-4": { "MyLibrary\\Tests\\": "tests/" } } } ``` ### include-path > **DEPRECATED**: This is only present to support legacy projects, and all new code > should preferably use autoloading. As such it is a deprecated practice, but the > feature itself will not likely disappear from Composer. A list of paths which should get appended to PHP's `include_path`. Example: ```json { "include-path": ["lib/"] } ``` Optional. ### target-dir > **DEPRECATED**: This is only present to support legacy PSR-0 style autoloading, > and all new code should preferably use PSR-4 without target-dir and projects > using PSR-0 with PHP namespaces are encouraged to migrate to PSR-4 instead. Defines the installation target. In case the package root is below the namespace declaration you cannot autoload properly. `target-dir` solves this problem. An example is Symfony. There are individual packages for the components. The Yaml component is under `Symfony\Component\Yaml`. The package root is that `Yaml` directory. To make autoloading possible, we need to make sure that it is not installed into `vendor/symfony/yaml`, but instead into `vendor/symfony/yaml/Symfony/Component/Yaml`, so that the autoloader can load it from `vendor/symfony/yaml`. To do that, `autoload` and `target-dir` are defined as follows: ```json { "autoload": { "psr-0": { "Symfony\\Component\\Yaml\\": "" } }, "target-dir": "Symfony/Component/Yaml" } ``` Optional. ### minimum-stability ([root-only](https://getcomposer.org/doc/04-schema.md.md#root-package)) This defines the default behavior for filtering packages by stability. This defaults to `stable`, so if you rely on a `dev` package, you should specify it in your file to avoid surprises. All versions of each package are checked for stability, and those that are less stable than the `minimum-stability` setting will be ignored when resolving your project dependencies. (Note that you can also specify stability requirements on a per-package basis using stability flags in the version constraints that you specify in a `require` block (see [package links](https://getcomposer.org/doc/04-schema.md.md#package-links) for more details). Available options (in order of stability) are `dev`, `alpha`, `beta`, `RC`, and `stable`. ### prefer-stable ([root-only](https://getcomposer.org/doc/04-schema.md.md#root-package)) When this is enabled, Composer will prefer more stable packages over unstable ones when finding compatible stable packages is possible. If you require a dev version or only alphas are available for a package, those will still be selected granted that the minimum-stability allows for it. Use `"prefer-stable": true` to enable. ### repositories ([root-only](https://getcomposer.org/doc/04-schema.md.md#root-package)) Custom package repositories to use. By default Composer only uses the packagist repository. By specifying repositories you can get packages from elsewhere. Repositories are not resolved recursively. You can only add them to your main `composer.json`. Repository declarations of dependencies' `composer.json`s are ignored. The following repository types are supported: * **composer:** A Composer repository is a `packages.json` file served via the network (HTTP, FTP, SSH), that contains a list of `composer.json` objects with additional `dist` and/or `source` information. The `packages.json` file is loaded using a PHP stream. You can set extra options on that stream using the `options` parameter. * **vcs:** The version control system repository can fetch packages from git, svn, fossil and hg repositories. * **path:** Loads a package from a local directory, given as an absolute or relative path (wildcards are supported). Mostly useful for monolithic repositories; the package is symlinked into `vendor` when possible, and mirrored otherwise. * **package:** If you depend on a project that does not have any support for Composer whatsoever you can define the package inline using a `package` repository. You basically inline the `composer.json` object. * **artifact:** Loads packages from a local directory containing ZIP or TAR archives, each with a `composer.json` in its root. Useful for exchanging build artifacts when no repository can be hosted online. For more information on any of these, see [Repositories](https://getcomposer.org/doc/05-repositories.md.md). Example: ```json { "repositories": [ { "type": "composer", "url": "http://packages.example.com" }, { "type": "composer", "url": "https://packages.example.com", "options": { "ssl": { "verify_peer": "true" } } }, { "type": "vcs", "url": "https://github.com/Seldaek/monolog" }, { "type": "path", "url": "../packages/my-package" }, { "type": "package", "package": { "name": "smarty/smarty", "version": "3.1.7", "dist": { "url": "https://www.smarty.net/files/Smarty-3.1.7.zip", "type": "zip" }, "source": { "url": "https://smarty-php.googlecode.com/svn/", "type": "svn", "reference": "tags/Smarty_3_1_7/distribution/" } } } ] } ``` > **Note:** Order is significant here. When looking for a package, Composer will look from the first to the last repository, and pick the first match. By default Packagist is added last which means that custom repositories can override packages from it. Using JSON object notation is also possible. However, JSON key/value pairs are to be considered unordered so consistent behaviour cannot be guaranteed and is deprecated. ```json { "repositories": { "foo": { "type": "composer", "url": "http://packages.foo.com" } } } ``` It will be superseded by the name property ```json { "repositories": [ { "name": "foo", "type": "composer", "url": "http://packages.foo.com" } ] } ``` ### config ([root-only](https://getcomposer.org/doc/04-schema.md.md#root-package)) A set of configuration options. It is only used for projects. See [Config](https://getcomposer.org/doc/06-config.md.md) for a description of each individual option. ### scripts ([root-only](https://getcomposer.org/doc/04-schema.md.md#root-package)) Composer allows you to hook into various parts of the installation process through the use of scripts. See [Scripts](https://getcomposer.org/doc/articles/scripts.md.md) for events details and examples. ### scripts-descriptions ([root-only](https://getcomposer.org/doc/04-schema.md.md#root-package)) Descriptions for the custom commands defined in `scripts`, shown by `composer list` and `composer run -l` instead of the default "Runs the ... script as defined in composer.json". ```json { "scripts-descriptions": { "test": "Run all tests!" } } ``` `composer validate` warns about a description given for a script that does not exist. See [Scripts](https://getcomposer.org/doc/articles/scripts.md.md#custom-descriptions) for more details. Optional. ### scripts-aliases ([root-only](https://getcomposer.org/doc/04-schema.md.md#root-package)) Alternate names for the custom commands defined in `scripts`, as an array of strings per script. Available as of Composer 2.7. ```json { "scripts-aliases": { "phpstan": ["stan", "analyze"] } } ``` `composer validate` warns about aliases given for a script that does not exist. See [Scripts](https://getcomposer.org/doc/articles/scripts.md.md#custom-aliases) for more details. Optional. ### extra Arbitrary extra data for consumption by `scripts`. This can be virtually anything. To access it from within a script event handler, you can do: ```php $extra = $event->getComposer()->getPackage()->getExtra(); ``` Optional. ### bin A set of files that should be treated as binaries and made available into the `bin-dir` (from config). Each entry is a path relative to the package root. It must not contain a `..` segment, nor any of the characters ``*$`"&^|<>()%!;`` or control characters: those cannot be represented safely in the proxy files Composer generates in the `bin-dir`. Wildcards are not expanded, a `bin/*` entry is simply a file that does not exist. See [Vendor Binaries](https://getcomposer.org/doc/articles/vendor-binaries.md.md) for more details. Optional. ### archive A set of options for creating package archives. The following options are supported: * **name:** Allows configuring base name for archive. By default (if not configured, and `--file` is not passed as command-line argument), `preg_replace('#[^a-z0-9-_]#i', '-', name)` is used. Example: ```json { "name": "org/strangeName", "archive": { "name": "Strange_name" } } ``` * **exclude:** Allows configuring a list of patterns for excluded paths. The pattern syntax matches .gitignore files. A leading exclamation mark (!) will result in any matching files to be included even if a previous pattern excluded them. A leading slash will only match at the beginning of the project relative path. An asterisk will not expand to a directory separator. Example: ```json { "archive": { "exclude": ["/foo/bar", "baz", "/*.test", "!/foo/bar/baz"] } } ``` The example will include `/dir/foo/bar/file`, `/foo/bar/baz`, `/file.php`, `/foo/my.test` but it will exclude `/foo/bar/any`, `/foo/baz`, and `/my.test`. Optional. ### php-ext Settings for a PHP extension package, read by [PIE](https://github.com/php/pie) rather than by Composer itself. It can only be set by packages whose [type](https://getcomposer.org/doc/04-schema.md.md#type) is `php-ext` or `php-ext-zend`, the two types reserved for extensions written in C. `composer validate` reports an error on any other package. See [PIE for extension maintainers](https://github.com/php/pie/blob/HEAD/docs/extension-maintainers.md#the-php-ext-definition) for the settings it accepts. Optional. ### abandoned Indicates whether this package has been abandoned. It can be boolean or a package name/URL pointing to a recommended alternative. Examples: Use `"abandoned": true` to indicate this package is abandoned. Use `"abandoned": "monolog/monolog"` to indicate this package is abandoned, and that the recommended alternative is `monolog/monolog`. Defaults to false. Optional. ### _comment Top level key used as a place to store comments (it can be a string or array of strings). ```json { "_comment": [ "The package foo/bar was required for business logic", "Remove package foo/baz when removing foo/bar" ] } ``` Defaults to empty. Optional. ### default-branch Indicates whether this version is the default branch of the VCS repository the package was read from. This one is for Composer's own use, do not set it in `composer.json`. Composer discards whatever the file contains and sets it itself, to `true` on the branch that the repository reports as its default one and on nothing else. It ends up in the metadata that `composer` repositories serve, which is where you may see it. Defaults to `false`. ### non-feature-branches A list of regex patterns of branch names that are non-numeric (e.g. "latest" or something), that will NOT be handled as feature branches. This is an array of strings. If you have non-numeric branch names, for example like "latest", "current", "latest-stable" or something, that do not look like a version number, then Composer handles such branches as feature branches. This means it searches for parent branches, that look like a version or ends at special branches (like master), and the root package version number becomes the version of the parent branch or at least master or something. To handle non-numeric named branches as versions instead of searching for a parent branch with a valid version or special branch name like master, you can set patterns for branch names that should be handled as dev version branches. This is really helpful when you have dependencies using "self.version", so that not dev-master, but the same branch is installed (in the example: latest-testing). An example: If you have a testing branch, that is heavily maintained during a testing phase and is deployed to your staging environment, normally `composer show -s` will give you `versions : * dev-master`. If you configure `latest-.*` as a pattern for non-feature-branches like this: ```json { "non-feature-branches": ["latest-.*"] } ``` Then `composer show -s` will give you `versions : * dev-latest-testing`. Optional. ← [Command-line interface](https://getcomposer.org/doc/03-cli.md.md) | [Repositories](https://getcomposer.org/doc/05-repositories.md.md) → --- Source: https://getcomposer.org/doc/05-repositories.md # Repositories This chapter will explain the concept of packages and repositories, what kinds of repositories are available, and how they work. ## Concepts Before we look at the different types of repositories that exist, we need to understand some basic concepts that Composer is built on. ### Package Composer is a dependency manager. It installs packages locally. A package is essentially a directory containing something. In this case it is PHP code, but in theory it could be anything. And it contains a package description which has a name and a version. The name and the version are used to identify the package. In fact, internally, Composer sees every version as a separate package. While this distinction does not matter when you are using Composer, it's quite important when you want to change it. In addition to the name and the version, there is useful metadata. The information most relevant for installation is the source definition, which describes where to get the package contents. The package data points to the contents of the package. And there are two options here: dist and source. **Dist:** The dist is a packaged version of the package data. Usually a released version, usually a stable release. **Source:** The source is used for development. This will usually originate from a source code repository, such as git. You can fetch this when you want to modify the downloaded package. Packages can supply either of these, or even both. Depending on certain factors, such as user-supplied options and stability of the package, one will be preferred. ### Repository A repository is a package source. It's a list of packages/versions. Composer will look in all your repositories to find the packages your project requires. By default, only the Packagist.org repository is registered in Composer. You can add more repositories to your project by declaring them in `composer.json`. Repositories are only available to the root package and the repositories defined in your dependencies will not be loaded. Read the [FAQ entry](https://getcomposer.org/doc/faqs/why-cant-composer-load-repositories-recursively.md.md) if you want to learn why. When resolving dependencies, packages are looked up from repositories from top to bottom, and by default, as soon as a package is found in one, Composer stops looking in other repositories. Read the [repository priorities](https://getcomposer.org/doc/articles/repository-priorities.md.md) article for more details and to see how to change this behavior. ## Types ### Composer The main repository type is the `composer` repository. It uses a single `packages.json` file that contains all of the package metadata. This is also the repository type that packagist uses. To reference a `composer` repository, supply the path before the `packages.json` file. In the case of packagist, that file is located at `/packages.json`, so the URL of the repository would be `repo.packagist.org`. For `example.org/packages.json` the repository URL would be `example.org`. ```json { "repositories": [ { "type": "composer", "url": "https://example.org" } ] } ``` #### packages The only required field is `packages`. The JSON structure is as follows: ```json { "packages": { "vendor/package-name": { "dev-master": { @composer.json }, "1.0.x-dev": { @composer.json }, "0.0.1": { @composer.json }, "1.0.0": { @composer.json } } } } ``` The `@composer.json` marker would be the contents of the `composer.json` from that package version including as a minimum: * name * version * dist or source Here is a minimal package definition: ```json { "name": "smarty/smarty", "version": "3.1.7", "dist": { "url": "https://www.smarty.net/files/Smarty-3.1.7.zip", "type": "zip" } } ``` It may include any of the other fields specified in the [schema](https://getcomposer.org/doc/04-schema.md.md). #### notify-batch The `notify-batch` field allows you to specify a URL that will be called every time a user installs a package. The URL can be either an absolute path (that will use the same domain as the repository), or a fully qualified URL. An example value: ```json { "notify-batch": "/downloads/" } ``` For `example.org/packages.json` containing a `monolog/monolog` package, this would send a `POST` request to `example.org/downloads/` with following JSON request body: ```json { "downloads": [ {"name": "monolog/monolog", "version": "1.2.1.0"} ] } ``` The version field will contain the normalized representation of the version number. This field is optional. #### metadata-url, available-packages and available-package-patterns The `metadata-url` field allows you to provide a URL template to serve all packages which are in the repository. It must contain the placeholder `%package%`. This field is new in Composer v2, and is prioritised over the `provider-includes` and `providers-url` fields if both are present. For compatibility with both Composer v1 and v2 you ideally want to provide both. New repository implementations may only need to support v2 however. An example: ```json { "metadata-url": "/p2/%package%.json" } ``` Whenever Composer looks for a package, it will replace `%package%` by the package name, and fetch that URL. If dev stability is allowed for the package, it will also load the URL again with `$packageName~dev` (e.g. `/p2/foo/bar~dev.json` to look for `foo/bar`'s dev versions). The `foo/bar.json` and `foo/bar~dev.json` files containing package versions MUST contain only versions for the foo/bar package, as `{"packages":{"foo/bar":[ ... versions here ... ]}}`. Caching is done via the use of If-Modified-Since header, so make sure you return Last-Modified headers and that they are accurate. The array of versions can also optionally be minified using `Composer\MetadataMinifier\MetadataMinifier::minify()` from [composer/metadata-minifier](https://packagist.org/packages/composer/metadata-minifier). If you do that, you should add a `"minified": "composer/2.0"` key at the top level to indicate to Composer it must expand the version list back into the original data. See https://repo.packagist.org/p2/monolog/monolog.json for an example. Any requested package which does not exist MUST return a 404 status code, which will indicate to Composer that this package does not exist in your repository. Make sure the 404 response is fast to avoid blocking Composer. Avoid redirects to alternative 404 pages. If your repository only has a small number of packages, and you want to avoid the 404-requests, you can also specify an `"available-packages"` key in `packages.json` which should be an array with all the package names that your repository contains. Alternatively you can specify an `"available-package-patterns"` key which is an array of package name patterns (with `*` matching any string, e.g. `vendor/*` would make Composer look up every matching package name in this repository). This field is optional. #### providers-api The `providers-api` field allows you to provide a URL template to serve all packages which provide a given package name, but not the package which has that name even if it exists. It must contain the placeholder `%package%`. For example https://packagist.org/providers/psr/log-implementation.json lists some package which have a "provide" rule for psr/log-implementation. ```json { "providers-api": "https://packagist.org/providers/%package%.json", } ``` This field is optional. #### list The `list` field allows you to return the names of packages which match a given filter (or all names if no filter is present). It should accept an optional `?filter=xx` query param, which can contain `*` as wildcards matching any substring. Replace/provide rules should not be considered here. It must return an array of package names: ```json { "packageNames": [ "a/b", "c/d" ] } ``` See for example. This field is optional. #### provider-includes and providers-url The `provider-includes` field allows you to list a set of files that list package names provided by this repository. The hash should be a sha256 of the files in this case. The `providers-url` describes how provider files are found on the server. It is an absolute path from the repository root. It must contain the placeholders `%package%` and `%hash%`. These fields are used by Composer v1, or if your repository does not have the `metadata-url` field set. An example: ```json { "provider-includes": { "providers-a.json": { "sha256": "f5b4bc0b354108ef08614e569c1ed01a2782e67641744864a74e788982886f4c" }, "providers-b.json": { "sha256": "b38372163fac0573053536f5b8ef11b86f804ea8b016d239e706191203f6efac" } }, "providers-url": "/p/%package%$%hash%.json" } ``` Those files contain lists of package names and hashes to verify the file integrity, for example: ```json { "providers": { "acme/foo": { "sha256": "38968de1305c2e17f4de33aea164515bc787c42c7e2d6e25948539a14268bb82" }, "acme/bar": { "sha256": "4dd24c930bd6e1103251306d6336ac813b563a220d9ca14f4743c032fb047233" } } } ``` The file above declares that acme/foo and acme/bar can be found in this repository, by loading the file referenced by `providers-url`, replacing `%package%` by the vendor namespaced package name and `%hash%` by the sha256 field. Those files themselves contain package definitions as described [above](https://getcomposer.org/doc/05-repositories.md.md#packages). These fields are optional. You probably don't need them for your own custom repository. #### Rate limiting and warnings A repository which needs to turn requests away for a while should respond with `429 Too Many Requests` and a `Retry-After` header, either as a number of seconds or as an HTTP date. When the interval is 60 seconds or less, Composer waits it out and retries the request, up to three times. The interval is taken to apply to the whole repository, so no further request to it, new or retried, is sent before the latest interval it asked for has passed. Requests to other repositories keep downloading in the meantime. A longer interval is not waited for, and the request fails with a message which says how long the repository asked to wait. A `429` without a `Retry-After` header is not retried. `Retry-After` is also honoured on the status codes Composer already retries, such as `503 Service Unavailable`. There, an interval longer than 60 seconds is ignored and Composer retries on its usual short backoff. To tell users why they are limited, and how to raise the limit, return a JSON body with a `warning` key and an `application/json` content type: ```http HTTP/1.1 429 Too Many Requests Retry-After: 30 Content-Type: application/json {"warning": "Anonymous requests are limited to 100 per minute, authenticate to raise the limit"} ``` Composer shows the warning whether it then retries or fails. When many parallel requests are limited at once, the warning and the notice that Composer is waiting are each shown once per repository, not once per request. #### cURL or stream options The repository is accessed either using cURL (Composer 2 with ext-curl enabled) or PHP streams. You can set extra options using the `options` parameter. For PHP streams, you can set any valid PHP stream context option. See [Context options and parameters](https://php.net/manual/en/context.php) for more information. When cURL is used, only a limited set of `http` and `ssl` options can be configured. ```json { "repositories": [ { "type": "composer", "url": "https://example.org", "options": { "http": { "timeout": 60 } } } ], "require": { "acme/package": "^1.0" } } ``` #### filter A Composer repository can advertise filter list support to clients by including a `filter` object in its `packages.json` response. This tells Composer that the repository provides filter list data and describes what lists are available. ```json { "metadata-url": "/p2/%package%.json", "filter": { "metadata": true, "lists": { "malware": { "enabled": true }, "typosquatting": { "enabled": true } }, "summary-url": "/p2/filter-summary.json" } } ``` - **`metadata`** (required, boolean) — Set to `true` to indicate that per-package metadata files (served via `metadata-url`) contain filter list data. Composer will fetch the metadata for each relevant package and look for a `filter` key containing list entries. - **`lists`** (required, object) — The names of all filter lists this repository provides, mapped to an object describing the list. The object currently carries an `enabled` flag (set to `true` when the list is available) and is structured this way so future per-list metadata can be added without breaking the wire format. - **`summary-url`** (optional, string) — A URL (absolute or root-relative) returning a compact mapping of list name → package name → version constraint. When configured, Composer fetches this endpoint during `composer install`, `composer update` and `composer audit` and uses it to skip per-package metadata fetches for packages that cannot match any active list. The summary endpoint must return JSON of the form: ```json { "filter": { "malware": { "vendor/package": ">=1.0.0,<1.2.0", "other/package": "*" } } } ``` Composer revalidates the cached summary via `If-Modified-Since` on every install/update/audit, using the same on-disk repository cache as package metadata. - **`api-url`** (optional, string) — A URL (absolute or root-relative) that accepts a POST request with the relevant package PURLs and configured list names, and replies with the matching filter entries directly. When set, Composer uses `api-url` instead of `summary-url` and per-package metadata for filter purposes; this is useful when the summary would be too large to serve in full. If both `summary-url` and `api-url` are advertised, `api-url` takes precedence and `summary-url` is ignored. Implementors should be aware that large amounts (a few hundreds would be normal) of package names can be submitted by Composer. You can decide to cap that list and return only the first 1000 or whatever you decide but make sure to limit this somehow. The endpoint receives a JSON body of the form: ```json { "packages": ["pkg://composer/vendor/package", "pkg://composer/other/package"], "lists": ["malware"] } ``` and must return JSON of the form: ```json { "filter": { "malware": [ { "package": "vendor/package", "constraint": ">=1.0.0,<1.2.0", "url": "https://example.org/filters/123", "reason": "Malware", "id": "PKFE-xxxx-xxxx-xxxx" } ] } } ``` Each entry has the same shape as a per-package metadata filter entry, with the addition of the `package` field (since one response covers many packages). The `api-url` POST is not cached client-side because each request body is different. Per-package metadata files should include a `filter` key whose value is an object mapping list names to arrays of filter entries: ```json { "packages": { "vendor/package": [{ ... }] }, "filter": { "malware": [ { "constraint": ">=1.0.0,<1.2.0", "url": "https://example.org/filters/123", "reason": "Malware", "id": "PKFE-xxxx-xxxx-xxxx" } ] } } ``` In a `composer.json` file, the `filter` key on a repository definition controls which lists advertised by that repository are honoured for audit reports and version blocking. Set `filter: false` to opt out of every list this repository advertises: ```json { "repositories": [ { "type": "composer", "url": "https://example.org", "filter": false } ] } ``` Set `filter` to an object listing advertised list names that should be skipped from this repository. ```json { "repositories": [ { "type": "composer", "url": "https://example.org", "filter": { "untrusted-list": false } } ] } ``` The repo-level `filter` only narrows what this repository contributes; it cannot enable a list that is not configured globally under [`config.policy`](https://getcomposer.org/doc/06-config.md.md#policy). #### require-published-time Defaults to `true`. When the [cooldown policy](https://getcomposer.org/doc/06-config.md.md#cooldown) is active, Composer errors out and exits if a version from this repository carries no `published-time`, as the policy then cannot tell whether the version is new or old. Set it to `false` for repositories that cannot provide publication times, such as Satis-generated ones, to fall back to the `time` field of each package's `composer.json`. That field is set by the package author, so the protection is weaker. ```json { "repositories": [ { "type": "composer", "url": "https://packages.example.org", "require-published-time": false } ] } ``` ### VCS VCS stands for version control system. This includes versioning systems like git, svn, fossil or hg. Composer has a repository type for installing packages from these systems. #### Loading a package from a VCS repository There are a few use cases for this. The most common one is maintaining your own fork of a third party library. If you are using a certain library for your project, and you decide to change something in the library, you will want your project to use the patched version. If the library is on GitHub (this is the case most of the time), you can fork it there and push your changes to your fork. After that you update the project's `composer.json`. All you have to do is add your fork as a repository and update the version constraint to point to your custom branch. In `composer.json` only, you should prefix your custom branch name with `"dev-"` (without making it part of the actual branch name). For version constraint naming conventions see [Libraries](https://getcomposer.org/doc/02-libraries.md.md) for more information. Example assuming you patched monolog to fix a bug in the `bugfix` branch: ```json { "repositories": [ { "type": "vcs", "url": "https://github.com/igorw/monolog" } ], "require": { "monolog/monolog": "dev-bugfix" } } ``` When you run `php composer.phar update`, you should get your modified version of `monolog/monolog` instead of the one from packagist. Note that you should not rename the package unless you really intend to fork it in the long term, and completely move away from the original package. Composer will correctly pick your package over the original one since the custom repository has priority over packagist. If you want to rename the package, you should do so in the default (often master) branch and not in a feature branch, since the package name is taken from the default branch. Also note that the override will not work if you change the `name` property in your forked repository's `composer.json` file as this needs to match the original for the override to work. If other dependencies rely on the package you forked, it is possible to inline-alias it so that it matches a constraint that it otherwise would not. For more information [see the aliases article](https://getcomposer.org/doc/articles/aliases.md.md). #### Using private repositories Exactly the same solution allows you to work with your private repositories at GitHub and Bitbucket: ```json { "repositories": [ { "type": "vcs", "url": "git@ssh.bitbucket.org:vendor/my-private-repo.git" } ], "require": { "vendor/my-private-repo": "dev-master" } } ``` The only requirement is the installation of SSH keys for a git client. #### Git alternatives Git is not the only version control system supported by the VCS repository. The following are supported: * **Git:** [git-scm.com](https://git-scm.com) * **Subversion:** [subversion.apache.org](https://subversion.apache.org) * **Mercurial:** [mercurial-scm.org](https://www.mercurial-scm.org) * **Fossil**: [fossil-scm.org](https://www.fossil-scm.org/) To get packages from these systems you need to have their respective clients installed. That can be inconvenient. And for this reason there is special support for GitHub and Bitbucket that use the APIs provided by these sites, to fetch the packages without having to install the version control system. The VCS repository provides `dist`s for them that fetch the packages as zips. * **GitHub:** [github.com](https://github.com) (Git) * **Bitbucket:** [bitbucket.org](https://bitbucket.org) (Git) The VCS driver to be used is detected automatically based on the URL. However, should you need to specify one for whatever reason, you can use `bitbucket`, `github`, `gitlab`, `perforce`, `fossil`, `git`, `svn` or `hg` as the repository type instead of `vcs`. If you set the `no-api` key to `true` on a github repository it will clone the repository as it would with any other git repository instead of using the GitHub API. But unlike using the `git` driver directly, Composer will still attempt to use github's zip files. Please note: * **To let Composer choose which driver to use** the repository type needs to be defined as "vcs" * **If you already used a private repository**, this means Composer should have cloned it in cache. If you want to install the same package with drivers, remember to launch the command `composer clearcache` followed by the command `composer update` to update Composer cache and install the package from dist. * VCS driver `git-bitbucket` is deprecated in favor of `bitbucket` #### Restricting the loaded branches Repositories with a large number of branches can be slow to load, as the `composer.json` of every branch has to be read. You can restrict which branches are loaded with the `only-branches` key, which takes a list of branch names that may contain `*` wildcards. The default branch is always loaded, so an empty list loads only the default branch. ```json { "repositories": [ { "type": "vcs", "url": "https://github.com/symfony/symfony", "only-branches": ["7.4", "8.*"] } ] } ``` The `exclude-branches` key does the opposite and skips the branches matching its patterns, which lets you leave out bot-managed or otherwise short-lived branches. Both keys can be combined, in which case a branch is loaded only if it matches `only-branches` and does not match `exclude-branches`. ```json { "repositories": [ { "type": "vcs", "url": "https://github.com/acme/foo", "exclude-branches": ["dependabot/*", "renovate/*", "gh-pages"] } ] } ``` Patterns are matched case-sensitively against the branch names as they appear in the repository (e.g. `7.4`, not `7.4.x-dev`). Tags are not affected by these options. > **Note:** For Mercurial and Perforce repositories the default branch is not > detected and thus not protected by these options, so make sure it is included > in `only-branches` (e.g. `default` for Mercurial, `master` for Perforce) and > not matched by `exclude-branches`, or it will be skipped. #### Bitbucket Driver Configuration > **Note that the repository endpoint for Bitbucket needs to be https rather than git.** After setting up your bitbucket repository, you will also need to [set up authentication](https://getcomposer.org/doc/articles/authentication-for-private-packages.md.md#bitbucket-oauth). #### Subversion Options Since Subversion has no native concept of branches and tags, Composer assumes by default that code is located in `$url/trunk`, `$url/branches` and `$url/tags`. If your repository has a different layout you can change those values. For example if you used capitalized names you could configure the repository like this: ```json { "repositories": [ { "type": "vcs", "url": "http://svn.example.org/projectA/", "trunk-path": "Trunk", "branches-path": "Branches", "tags-path": "Tags" } ] } ``` If you have no branches or tags directory you can disable them entirely by setting the `branches-path` or `tags-path` to `false`. If the package is in a subdirectory, e.g. `/trunk/foo/bar/composer.json` and `/tags/1.0/foo/bar/composer.json`, then you can make Composer access it by setting the `"package-path"` option to the sub-directory, in this example it would be `"package-path": "foo/bar/"`. If you have a private Subversion repository you can save credentials in the http-basic section of your config (See [Config](https://getcomposer.org/doc/06-config.md.md#http-basic)): ```json { "http-basic": { "svn.example.org": { "username": "username", "password": "password" } } } ``` If your Subversion client is configured to store credentials by default these credentials will be saved for the current user and existing saved credentials for this server will be overwritten. To change this behavior by setting the `"svn-cache-credentials"` option in your repository configuration: ```json { "repositories": [ { "type": "vcs", "url": "http://svn.example.org/projectA/", "svn-cache-credentials": false } ] } ``` ### Path The `path` repository allows you to depend on a local directory, either absolute or relative. This can be especially useful when dealing with monolithic repositories. For instance, if you have the following directory structure in your repository: ```text ... ├── apps │ └── my-app │ └── composer.json ├── packages │ └── my-package │ └── composer.json ... ``` Then, to add the package `my/package` as a dependency, in your `apps/my-app/composer.json` file, you can use the following configuration: ```json { "repositories": [ { "type": "path", "url": "../../packages/my-package" } ], "require": { "my/package": "*" } } ``` If the package is a local VCS repository, the version may be inferred by the branch or tag that is currently checked out. Otherwise, the version should be explicitly defined in the package's `composer.json` file. If the version cannot be resolved by these means, it is assumed to be `dev-master`. When the version cannot be inferred from the local VCS repository, or when you want to override the version, you can use the `versions` option when declaring the repository: ```json { "repositories": [ { "type": "path", "url": "../../packages/my-package", "options": { "versions": { "my/package": "4.2-dev" } } } ] } ``` The local package will be symlinked if possible, in which case the output in the console will read `Symlinking from ../../packages/my-package`. If symlinking is _not_ possible the package will be copied. In that case, the console will output `Mirrored from ../../packages/my-package`. Instead of default fallback strategy you can force to use symlink with `"symlink": true` or mirroring with `"symlink": false` option. Forcing mirroring can be useful when deploying or generating package from a monolithic repository. > **Note:** On Windows, directory symlinks are implemented using NTFS junctions > because they can be created by non-admin users. Mirroring will always be used > on versions below Windows 7 or if `proc_open` has been disabled. ```json { "repositories": [ { "type": "path", "url": "../../packages/*", "options": { "symlink": false } } ] } ``` Leading tildes are expanded to the current user's home folder, and environment variables are parsed in both Windows and Linux/Mac notations. For example `~/git/mypackage` will automatically load the mypackage clone from `/home//git/mypackage`, equivalent to `$HOME/git/mypackage` or `%USERPROFILE%/git/mypackage`. > **Note:** Repository paths can also contain wildcards like `*` and `?`. > For details, see the [PHP glob function](https://php.net/glob). You can configure the way the package's dist reference (which appears in the composer.lock file) is built. The following modes exist: - `none` - reference will be always null. This can help reduce lock file conflicts in the lock file but reduces clarity as to when the last update happened and whether the package is in the latest state. - `config` - reference is built based on a hash of the package's composer.json and repo config - `auto` (used by default) - reference is built basing on the hash like with `config`, but if the package folder contains a git repository, the HEAD commit's hash is used as reference instead. ```json { "repositories": [ { "type": "path", "url": "../../packages/*", "options": { "reference": "config" } } ] } ``` ### Package If you want to use a project that does not support Composer through any of the means above, you still can define the package yourself by using a `package` repository. Basically, you define the same information that is included in the `composer` repository's `packages.json`, but only for a single package. Again, the minimum required fields are `name`, `version`, and either of `dist` or `source`. Here is an example for the smarty template engine: ```json { "repositories": [ { "type": "package", "package": { "name": "smarty/smarty", "version": "3.1.7", "dist": { "url": "https://www.smarty.net/files/Smarty-3.1.7.zip", "type": "zip" }, "source": { "url": "http://smarty-php.googlecode.com/svn/", "type": "svn", "reference": "tags/Smarty_3_1_7/distribution/" }, "autoload": { "classmap": ["libs/"] } } } ], "require": { "smarty/smarty": "3.1.*" } } ``` Typically, you would leave the source part off, as you don't really need it. If a source key is included, the reference field should be a reference to the version that will be installed. Where the type field is `git`, this will the be the commit id, branch or tag name. > **Note**: It is not recommended to use a git branch name for the reference field. While this is valid since it is supported by `git checkout`, > branch names are mutable so cannot be locked. Where the type field is `svn`, the reference field should contain the reference that gets appended to the URL when running `svn co`. > **Note**: This repository type has a few limitations and should be avoided > whenever possible: > > - Composer will not update the package unless you change the `version` field. > - Composer will not update the commit references, so if you use `master` as > reference you will have to delete the package to force an update, and will > have to deal with an unstable lock file. The `"package"` key in a `package` repository may be set to an array to define multiple versions of a package: ```json { "repositories": [ { "type": "package", "package": [ { "name": "foo/bar", "version": "1.0.0", ... }, { "name": "foo/bar", "version": "2.0.0", ... } ] } ] } ``` ### Artifact There are some cases, when there is no ability to have one of the previously mentioned repository types online, even the VCS one. A typical example could be cross-organisation library exchange through build artifacts. Of course, most of the time these are private. To use these archives as-is, one can use a repository of type `artifact` with a folder containing ZIP or TAR archives of those private packages: ```json { "repositories": [ { "type": "artifact", "url": "path/to/directory/with/zips/" } ], "require": { "private-vendor-one/core": "15.6.2", "private-vendor-two/connectivity": "*", "acme-corp/parser": "10.3.5" } } ``` Each zip artifact is a ZIP archive with `composer.json` in root folder: ```shell unzip -l acme-corp-parser-10.3.5.zip ``` ```text composer.json ... ``` If there are two archives with different versions of a package, they are both imported. When an archive with a newer version is added in the artifact folder and you run `update`, that version will be imported as well and Composer will update to the latest version. ## Hosting your own While you will probably want to put your packages on packagist most of the time, there are some use cases for hosting your own repository. * **Private company packages:** If you are part of a company that uses Composer for their packages internally, you might want to keep those packages private. * **Separate ecosystem:** If you have a project which has its own ecosystem, and the packages aren't really reusable by the greater PHP community, you might want to keep them separate to packagist. An example of this would be WordPress plugins. For hosting your own packages, a native `composer` type of repository is recommended, which provides the best performance. There are a few tools that can help you create a `composer` repository. ### Private Packagist [Private Packagist](https://packagist.com/) is a hosted or self-hosted application providing private package hosting as well as mirroring of GitHub, Packagist.org and other package repositories. Check out [Packagist.com](https://packagist.com/) for more information. ### Satis Satis is a static `composer` repository generator. It is a bit like an ultra- lightweight, static file-based version of packagist. You give it a `composer.json` containing repositories, typically VCS and package repository definitions. It will fetch all the packages that are `require`d and dump a `packages.json` that is your `composer` repository. Check [the satis GitHub repository](https://github.com/composer/satis) and the [handling private packages article](https://getcomposer.org/doc/articles/handling-private-packages.md.md) for more information. ## Disabling Packagist.org You can disable the default Packagist.org repository by adding this to your `composer.json`: ```json { "repositories": [ { "packagist.org": false } ] } ``` You can disable Packagist.org globally by using the global config flag: ```shell php composer.phar config -g repo.packagist.org false ``` ← [Schema](https://getcomposer.org/doc/04-schema.md.md) | [Config](https://getcomposer.org/doc/06-config.md.md) → --- Source: https://getcomposer.org/doc/06-config.md # Config This chapter will describe the `config` section of the `composer.json` [schema](https://getcomposer.org/doc/04-schema.md.md). ## process-timeout The timeout in seconds for process executions, defaults to 300 (5mins). The duration processes like `git clone`s can run before Composer assumes they died out. You may need to make this higher if you have a slow connection or huge vendors. Example: ```json { "config": { "process-timeout": 900 } } ``` ### Disabling timeouts for an individual script command To disable the process timeout on a custom command under `scripts`, a static helper is available: ```json { "scripts": { "test": [ "Composer\\Config::disableProcessTimeout", "phpunit" ] } } ``` ## allow-plugins Defaults to `{}` which does not allow any plugins to be loaded. As of Composer 2.2.0, the `allow-plugins` option adds a layer of security allowing you to restrict which Composer plugins are able to execute code during a Composer run. When a new plugin is first activated, which is not yet listed in the config option, Composer will print a warning. If you run Composer interactively it will prompt you to decide if you want to execute the plugin or not. Use this setting to allow only packages you trust to execute code. Set it to an object with package name patterns as keys. The values are **true** to allow and **false** to disallow while suppressing further warnings and prompts. ```json { "config": { "allow-plugins": { "third-party/required-plugin": true, "my-organization/*": true, "unnecessary/plugin": false } } } ``` You can also set the config option itself to `false` to disallow all plugins, or `true` to allow all plugins to run (NOT recommended). For example: ```json { "config": { "allow-plugins": false } } ``` ## use-include-path Defaults to `false`. If `true`, the Composer autoloader will also look for classes in the PHP include path. ## preferred-install Defaults to `dist` and can be any of `source`, `dist` or `auto`. This option allows you to set the install method Composer will prefer to use. Can optionally be an object with package name patterns for keys for more granular install preferences. ```json { "config": { "preferred-install": { "my-organization/stable-package": "dist", "my-organization/*": "source", "partner-organization/*": "auto", "*": "dist" } } } ``` - `source` means Composer will install packages from their `source` if there is one. This is typically a git clone or equivalent checkout of the version control system the package uses. This is useful if you want to make a bugfix to a project and get a local git clone of the dependency directly. - `auto` is the legacy behavior where Composer uses `source` automatically for dev versions, and `dist` otherwise. - `dist` (the default as of Composer 2.1) means Composer installs from `dist`, where possible. This is typically a zip file download, which is faster than cloning the entire repository. > **Note:** Order matters. More specific patterns should be earlier than > more relaxed patterns. When mixing the string notation with the hash > configuration in global and package configurations the string notation > is translated to a `*` package pattern. > **Tip:** If you want a source checkout for some packages so you can make > local edits, but only on your own machine (not in CI), prefer configuring > `preferred-install` globally rather than committing it to the project. For > example: > > ``` > composer config --global preferred-install.my-vendor/* source > ``` > > CI then keeps installing from `dist` by default, while your dev machine > always pulls those packages from source. This avoids relying on a source > install failure to fall back to dist, and saves CI from attempting a clone > first, which keep the output leaner and your CI faster. ## source-fallback > **Deprecated:** This option is deprecated and will be removed in Composer 2.11. > Do not set it unless you absolutely need to. It exists as a temporary opt-in > while we disable the dist → source fallback for security reasons (silently > switching from a dist to a less-trusted or manipulated source checkout has > security implications). If you have a legitimate use case for re-enabling > the dist → source fallback and do not want us to remove it in 2.11, please > open an issue at https://github.com/composer/composer/issues to let us know. Defaults to `false`. When set to `true`, a failed **dist** install will fall back to a **source** checkout. This option only governs the dist → source direction; falling back from a failed source checkout to the dist artifact is always allowed regardless of this setting. ```json { "config": { "source-fallback": true } } ``` > **Note:** With this option at its default (`false`) and a dist download > failing, Composer throws an error immediately instead of trying a source > checkout. Make sure your preferred installation source (`preferred-install`) > is correctly configured. ## policy Unified dependency policy configuration. Controls Composer behavior for dependencies with security advisories, flagged as malware, abandoned packages, and custom dependency policies. Audit reports can be generated with `composer audit`; blocking prevents insecure or otherwise flagged package versions from being installed during `composer update`, `require`, or `remove`. The [malware](https://getcomposer.org/doc/06-config.md.md#block-scope) policy and [custom dependency policies](https://getcomposer.org/doc/06-config.md.md#block-scope-1) can additionally block during a `composer install` via their `block-scope` setting. Set to `false` to disable all dependency policy enforcement: ```json { "config": { "policy": false } } ``` > **Migrating from `config.audit`?** See > [How `config.audit` interacts with `config.policy`](https://getcomposer.org/doc/06-config.md.md#how-configaudit-interacts-with-configpolicy) > for how the legacy keys are still honored as a fallback while you migrate. ### advisories Configuration for packages affected by security advisories. #### block Defaults to `true`. When `true`, package versions with active security advisories are blocked and cannot be installed during `update`/`require`/`remove` unless the advisory or package is ignored. ```json { "config": { "policy": { "advisories": { "block": false } } } } ``` Advisories are matched against version numbers, so `dev-*` versions from branch names like `dev-main` are never blocked, even when required through an inline alias like `dev-main as 1.0.0`. Numeric branch names, which are turned into numbered dev versions like `3.3.x-dev`, and numeric branch aliases are matched normally. For example if `dev-main` has a branch alias of `3.3.x-dev`, an advisory affecting `<3.5` blocks requiring `^3.3`, but requiring `dev-main` explicitly still works. The audit still reports it though, as the installed code matches the advisory through its branch alias. For advisory authors, this means an advisory cannot target a named branch with a `dev-*` version directly, not even with `*` listed as the affected versions. To cover one, the affected versions must include its branch alias, like `3.3.x-dev` above. #### audit Defaults to `fail`. How `composer audit` treats packages with security advisories. - `ignore` — advisories are not reported - `report` — advisories are reported but do not cause a non-zero exit code - `fail` — advisories cause `composer audit` to exit with a non-zero code ```json { "config": { "policy": { "advisories": { "audit": "report" } } } } ``` #### ignore-id A list of advisory IDs (CVE, GHSA, PKSA, …) to ignore. Each entry can optionally include a reason and scoping (`on-block`/`on-audit`) to limit where the ignore applies. ##### Simple list: ```json { "config": { "policy": { "advisories": { "ignore-id": ["CVE-1234", "GHSA-xx"] } } } } ``` ##### With reasons: ```json { "config": { "policy": { "advisories": { "ignore-id": { "CVE-1234": "Not affected.", "GHSA-xx": "Patch applied." } } } } } ``` ##### With scoping: `on-block: false` means the advisory no longer blocks updates but is still reported in audit. `on-audit: false` means the advisory still blocks updates but is no longer reported in audit. ```json { "config": { "policy": { "advisories": { "ignore-id": { "CVE-1234": {"on-block": false, "reason": "Patch applied, still want blocking."}, "GHSA-xx": {"on-audit": false, "reason": "False positive, still report."} } } } } } ``` #### ignore A list of package names to ignore for security advisory handling. Supports wildcards and optional version constraints. See the [ignore format](https://getcomposer.org/doc/06-config.md.md#ignore-format) for all supported syntax variants. #### ignore-severity A list of advisory severity levels to ignore: `low`, `medium`, `high`, `critical`. ##### Simple list: ```json { "config": { "policy": { "advisories": { "ignore-severity": ["low", "medium"] } } } } ``` ##### With scoping: ```json { "config": { "policy": { "advisories": { "ignore-severity": { "low": {"on-block": false}, "medium": {"on-audit": false, "reason": "Handled via WAF"} } } } } } ``` ### abandoned Configuration for abandoned packages. #### block Defaults to `false`. When `true`, abandoned packages cannot be installed during `update`/`require`/`remove`. ```json { "config": { "policy": { "abandoned": { "block": true } } } } ``` #### audit Defaults to `fail`. How `composer audit` treats abandoned packages. - `ignore` — abandoned packages are not reported - `report` — abandoned packages are reported but do not cause a non-zero exit code - `fail` — abandoned packages cause `composer audit` to exit with a non-zero code ```json { "config": { "policy": { "abandoned": { "audit": "report" } } } } ``` Can be overridden via the [`COMPOSER_AUDIT_ABANDONED`](https://getcomposer.org/doc/03-cli.md.md#composer_audit_abandoned) environment variable or the [`--abandoned`](https://getcomposer.org/doc/03-cli.md.md#audit) CLI option. #### ignore A list of package names (or patterns) to ignore for the abandoned check, regardless of their abandoned state. See the [ignore format](https://getcomposer.org/doc/06-config.md.md#ignore-format) for all supported syntax variants. ```json { "config": { "policy": { "abandoned": { "ignore": { "acme/*": "Scheduled for replacement next quarter.", "vendor/legacy": {"on-block": false, "reason": "Allow in updates but still report."} } } } } } ``` ### malware Configuration for package versions flagged as containing malware. #### block Defaults to `true`. When `true`, package versions flagged as malware are blocked. #### block-scope Defaults to `all`. Controls which commands trigger blocking: - `all` — block during both `update`/`require`/`remove` and `install` - `update` — block only during `update`/`require`/`remove` - `install` — block only during `install` ```json { "config": { "policy": { "malware": { "block-scope": "update" } } } } ``` #### audit Defaults to `fail`. Same values as [advisories.audit](https://getcomposer.org/doc/06-config.md.md#audit). #### ignore Package names to exclude from malware checks. See the [ignore format](https://getcomposer.org/doc/06-config.md.md#ignore-format) for all supported syntax variants. #### ignore-source A list of source names to exclude from malware checks. ```json { "config": { "policy": { "malware": { "ignore-source": ["aikido"] } } } } ``` ### cooldown Withholds newly released package versions for a configurable period to reduce exposure to supply chain attacks. By introducing a waiting period before a new version becomes installable, you reduce the risk of pulling in a release that was compromised shortly after publication — many malicious versions are identified and removed within hours or days of being published. The cooldown policy applies when resolving dependencies during `composer update`/`require`. `composer require`, `init` and `create-project` also skip withheld versions when picking a version constraint or the project version, so that the constraint they write can be resolved. `composer outdated` and `composer show --latest` report the newest version the policy allows installing, and mark a newer release that is still in the cooldown period. The cooldown period is measured from the publication time reported by the package repository (`published-time`, which Packagist.org provides), as package authors cannot influence it. Composer repositories must provide it for every version Composer considers while a cooldown period is configured, otherwise the command errors out and names the package that lacks it. Set [`require-published-time`](https://getcomposer.org/doc/05-repositories.md.md#require-published-time) to `false` on a repository that cannot provide it to fall back to the `time` field of each package's `composer.json`. Packages from VCS, path or artifact repositories always use that fallback, and Composer says so when it withholds such a version. #### period A duration string in the form `" "` where the unit is one of `second`, `minute`, `hour`, `day` or `week` (lowercase, singular or plural — e.g. `"7 days"`, `"24 hours"`, `"30 minutes"`, `"1 week"`), an integer number of seconds, or `null` to disable. Relative phrases such as `"tomorrow"` or `"next week"` are rejected. Defaults to `null` (no cooldown period). The policy only takes effect once a period is set. ```json { "config": { "policy": { "cooldown": { "period": "7 days" } } } } ``` The following are never withheld by the cooldown policy: - **Dev versions** (e.g. `dev-main`) — they represent mutable branch state - **Locked packages that are not being updated** — a partial update (`composer update vendor/pkg`, `composer require`) keeps the locked version of every other package. A full `composer update` re-evaluates all versions, so a locked version still inside the cooldown period will be replaced by an older release, or the update fails if no other version satisfies the requirements - **Platform packages** — PHP, extensions and other platform requirements - **Packages without any publication date** — for example a version defined inline in a [`package` repository](https://getcomposer.org/doc/05-repositories.md.md#package-1) without a `time` field, or a path repository whose `composer.json` has none. Composer cannot tell how old such a version is and lets it through rather than blocking it forever. A Composer repository that omits `published-time` errors out instead, see above #### block Defaults to `true`. When `true`, versions still within the cooldown period cannot be installed during `update`/`require`. Set to `false` to skip blocking for a cooldown period entirely. #### ignore Packages listed under `ignore` bypass the cooldown policy. This uses the same [ignore format](https://getcomposer.org/doc/06-config.md.md#ignore-format) as the other policies, so each entry may carry a reason and an optional version constraint, and package names support wildcards (e.g. `vendor/*`). ```json { "config": { "policy": { "cooldown": { "period": "7 days", "ignore": { "mycompany/*": "We trust the code in our own packages", "symfony/security-bundle": "Security fixes need to be applied immediately" } } } } } ``` #### Bypassing the cooldown To bypass the cooldown for a single run, pass `--no-cooldown` to `update`, `require`, `remove` or `create-project`. Other policies still apply, unlike with `--no-blocking`. #### Environment variables `COMPOSER_POLICY_COOLDOWN_PERIOD` overrides the configured `period` (the `ignore` rules from `composer.json` are still respected), and `COMPOSER_POLICY_COOLDOWN_BLOCK` overrides `block`. A non-zero `COMPOSER_POLICY_COOLDOWN_PERIOD` also enables the cooldown policy when `cooldown` is set to `false`, but is ignored when the whole `policy` config is set to `false`: ```bash # Disable the cooldown policy temporarily COMPOSER_POLICY_COOLDOWN_PERIOD=0 composer update # Set a specific duration COMPOSER_POLICY_COOLDOWN_PERIOD="24 hours" composer update ``` ### ignore-unreachable Defaults to `["update", "install"]`. When the operation is listed here, repositories and policies with URL sources that are unreachable or return a non-200 response are silently ignored rather than causing an error. Useful in environments where not all package repositories are accessible. Set to `true` to ignore unreachable repositories and custom dependency policy sources for all operations and to `false` to ignore them for no operations. Possible values are: `audit`, `install`, and `update`. ```json { "config": { "policy": { "ignore-unreachable": ["install", "update", "audit"] } } } ``` ### Custom dependency policies In addition to the built-in `advisories`, `malware`, and `abandoned` dependency policies, you can define named custom dependency policies. A custom dependency policy needs its own set of package versions, supplied by one or more sources (advertised by package repositories or set explicitly here). ```json { "config": { "policy": { "my-policy": { "block": true, "audit": "fail", "sources": [ {"type": "url", "url": "https://example.org/my-bad-packages-list.json"} ], "ignore": { "vendor/package": "Assessed and accepted." } } } } } ``` Source URLs must use `https://`. `http://` and other schemes are rejected both at schema validation time (`composer validate`) and at config load time. A `url` source is queried the same way as a repository's [`api-url`](https://getcomposer.org/doc/05-repositories.md.md#filter): Composer sends a POST request with the relevant package PURLs and the custom dependency policy name, and expects the matching filter entries back. The request is not cached client-side because each request body is different. Implementors should be aware that large amounts (a few hundred would be normal) of package names can be submitted. The submitted PURLs are the full set of candidate package names gathered *before* dependency resolution, so they identify packages by name only (no version constraints yet), and not every submitted package will necessarily be selected by the resolver afterwards. The endpoint receives a JSON body of the form: ```json { "packages": ["pkg://composer/vendor/package", "pkg://composer/other/package"], "lists": ["my-policy"] } ``` The request body reuses the wire format of a Composer repository's [`api-url`](https://getcomposer.org/doc/05-repositories.md.md#filter). There, a single endpoint can serve several named filter lists (for example `malware` and `typosquatting`), so `lists` is an array naming which of them Composer wants, and the response is a `filter` object keyed by list name. A custom dependency policy has no such multiplexing: its `url` source exists only to serve that one policy. Composer therefore always sends the policy name as the sole element of `lists` (so the array carries exactly one value here), and the endpoint should treat any list name it receives as referring to that policy. The endpoint must return JSON of the form: ```json { "filter": [ { "package": "vendor/package", "constraint": ">=1.0.0,<1.2.0", "url": "https://example.org/filters/123", "reason": "Assessed and rejected.", "id": "PKFE-xxxx-xxxx-xxxx" } ] } ``` Because the `url` source only ever serves this one policy, the response drops the per-list keying used by a repository's `api-url` (where `filter` is an object mapping each requested list name to its entries). Here `filter` is instead a flat array of entries that all belong to this policy. The `package` and `constraint` fields are required on each entry; `url`, `reason`, and `id` are optional. Entries whose package does not match a package in the request are ignored. Custom dependency policy names must not conflict with the reserved names `advisories`, `malware`, or `abandoned`, and must not start with `ignore` (the only `ignore`-prefixed key allowed at this level is the documented `ignore-unreachable` setting). The following names are reserved for future built-in dependency policies and cannot be used as custom dependency policy names: `package`, `packages`, `license`, `licence`, `licenses`, `licences`, `support`, `maintenance`, `security`, `minimum-release-age`. Composer rejects any colliding key both at schema validation time (`composer validate`) and at config load time. #### block-scope Defaults to `update`. Controls which commands trigger blocking for this custom policy: - `all` — block during both `update`/`require`/`remove` and `install` - `update` — block only during `update`/`require`/`remove` - `install` — block only during `install` Unlike the [`malware`](https://getcomposer.org/doc/06-config.md.md#malware) policy (which defaults to `all`), custom dependency policies default to `update`, so they only block during `composer install` when you opt in with `block-scope` set to `install` or `all`. This is useful for enforcing a policy in environments where only `composer install` runs, such as CI or deployment. ```json { "config": { "policy": { "my-policy": { "block-scope": "all" } } } } ``` ### ignore format The `ignore` key on every dependency policy accepts package name patterns with optional version constraints and per-rule scoping. All formats may be mixed in the same map. ##### Simple list (ignore all versions): ```json { "config": { "policy": { "": { "ignore": ["vendor/package", "acme/*"] } } } } ``` ##### With reason: ```json { "config": { "policy": { "": { "ignore": { "vendor/package": "Assessed, no risk." } } } } } ``` ##### With version constraint: ```json { "config": { "policy": { "": { "ignore": { "vendor/package": {"constraint": "^2.0", "reason": "Only v2 is affected."} } } } } } ``` ##### With scoping: `on-block: false` ignores only for audit (the package is still blocked during updates as on-block ignoring is disabled). `on-audit: false` ignores only for blocking (the package is still reported in audit). ```json { "config": { "policy": { "": { "ignore": { "vendor/package": {"on-audit": false, "reason": "Workaround applied; keep reporting."} } } } } } ``` ##### Multiple rules for the same package: ```json { "config": { "policy": { "": { "ignore": { "vendor/package": [ {"constraint": "^1.0", "on-audit": false}, {"constraint": "^2.0", "reason": "v2 is patched."} ] } } } } } ``` ## audit > **Deprecated.** Use [`config.policy`](https://getcomposer.org/doc/06-config.md.md#policy) instead. All `config.audit` keys are still > supported for backwards compatibility but will be removed in a future major version. Security audit and version blocking configuration options. Audit reports can be generated with `composer audit` and short format versions are automatically reported at the end of update or require commands. Version blocking discards package versions identified as insecure or abandoned, depending on configuration, before resolving dependencies, ensuring they cannot be installed. ### How `config.audit` interacts with `config.policy` The legacy `config.audit` keys are only read as a fallback when the corresponding [`config.policy`](https://getcomposer.org/doc/06-config.md.md#policy) section is **absent**. The fallback is all-or-nothing per built-in dependency policy: - If [`config.policy.advisories`](https://getcomposer.org/doc/06-config.md.md#advisories) is set (to any value, including `false`), every advisories-related `audit.*` key ([`audit.block-insecure`](https://getcomposer.org/doc/06-config.md.md#block-insecure), [`audit.ignore`](https://getcomposer.org/doc/06-config.md.md#ignore-3), [`audit.ignore-severity`](https://getcomposer.org/doc/06-config.md.md#ignore-severity-1)) is **ignored entirely** — only [`policy.advisories.block`](https://getcomposer.org/doc/06-config.md.md#block), [`policy.advisories.ignore`](https://getcomposer.org/doc/06-config.md.md#ignore), and [`policy.advisories.ignore-severity`](https://getcomposer.org/doc/06-config.md.md#ignore-severity) are read. Mix-and-matching, e.g. setting `policy.advisories.block` while expecting `audit.ignore-severity` to still apply, is not supported. Migrate all advisories-related settings together. - If [`config.policy.abandoned`](https://getcomposer.org/doc/06-config.md.md#abandoned) is set (to any value, including `false`), every abandoned-related `audit.*` key ([`audit.block-abandoned`](https://getcomposer.org/doc/06-config.md.md#block-abandoned), [`audit.abandoned`](https://getcomposer.org/doc/06-config.md.md#abandoned-1), [`audit.ignore-abandoned`](https://getcomposer.org/doc/06-config.md.md#ignore-abandoned)) is **ignored entirely** — only [`policy.abandoned.block`](https://getcomposer.org/doc/06-config.md.md#block-1), [`policy.abandoned.audit`](https://getcomposer.org/doc/06-config.md.md#audit-1), and [`policy.abandoned.ignore`](https://getcomposer.org/doc/06-config.md.md#ignore-1) are read. - The two built-in dependency policies are independent: configuring `policy.advisories` while leaving the abandoned settings under `audit.*` is allowed and vice versa. - Setting [`policy.ignore-unreachable`](https://getcomposer.org/doc/06-config.md.md#ignore-unreachable) supersedes the legacy [`audit.ignore-unreachable`](https://getcomposer.org/doc/06-config.md.md#ignore-unreachable-1) key. ### ignore > **Deprecated.** Use [`config.policy.advisories.ignore-id`](https://getcomposer.org/doc/06-config.md.md#ignore-id) for advisory IDs > (CVE, GHSA, PKSA) and [`config.policy.advisories.ignore`](https://getcomposer.org/doc/06-config.md.md#ignore) for package names instead. > Note: the new format uses `on-block`/`on-audit` booleans instead of `"apply": "audit|block|all"`. A list of advisory ids, remote ids, CVE ids or package names (not recommended) that are ignored in audit reports and/or version blocking. #### Simple format with reasons: ```json { "config": { "audit": { "ignore": { "CVE-1234": "The affected component is not in use.", "GHSA-xx": "The security fix was applied as a patch.", "PKSA-yy": "Due to mitigations in place the update can be delayed." } } } } ``` #### Simple format without reasons: ```json { "config": { "audit": { "ignore": ["CVE-1234", "GHSA-xx", "PKSA-yy"] } } } ``` #### Detailed format with apply scope: The detailed format allows you to control whether an ignore applies to audit reports only, version blocking only, or both. The `apply` field accepts: - `audit` - Only ignore for audit reports (advisory doesn't appear in audit reports, but package is still blocked during updates) - `block` - Only ignore for version blocking (package can be used during updates, but advisory still appears in audit reports) - `all` - Ignore during audit reports and version blocking (default behavior) ```json { "config": { "audit": { "ignore": { "CVE-1234": { "apply": "audit", "reason": "Not applicable to us, so don't report, but still want to make sure we don't use this version in updates." }, "GHSA-xx": { "apply": "block", "reason": "Workaround applied, can only fix next week, allow during updates but still report in audits" }, "PKSA-yy": { "apply": "all", "reason": "False report, Ignore completely in all contexts" } } } } } ``` All formats can be mixed together in the same configuration. ### abandoned > **Deprecated.** Use [`config.policy.abandoned.audit`](https://getcomposer.org/doc/06-config.md.md#audit-1) instead. Defaults to `fail` since Composer 2.7 (defaulted to `report` in Composer 2.6 that added the option). Defines whether and how audit reports should report abandoned packages. There are three possible values: - `ignore` means audit reports do not consider abandoned packages at all. - `report` means abandoned packages are reported as an error but do not cause the composer audit command return a non-zero exit code. - `fail` means abandoned packages will cause the audit command to fail with a non-zero exit code. Note, that this only applies to audit reports, this setting does not impact the blocking of insecure package versions. To configure blocking of abandoned packages, see the [`block-abandoned`](https://getcomposer.org/doc/06-config.md.md#block-abandoned) option. ```json { "config": { "audit": { "abandoned": "report" } } } ``` Since Composer 2.7, the option can be overridden via the [`COMPOSER_AUDIT_ABANDONED`](https://getcomposer.org/doc/03-cli.md.md#composer_audit_abandoned) environment variable. Since Composer 2.8, the option can be overridden via the [`--abandoned`](https://getcomposer.org/doc/03-cli.md.md#audit) command line option, which overrides both the config value and the environment variable. ### ignore-abandoned > **Deprecated.** Use [`config.policy.abandoned.ignore`](https://getcomposer.org/doc/06-config.md.md#ignore-1) instead. > Note: the new format uses `on-block`/`on-audit` booleans instead of `"apply": "audit|block|all"`. A list of abandoned package names that are ignored for audit reports and/or version blocking. Allows you to select packages that you want to keep using despite their abandoned state. #### Simple format with reasons: ```json { "config": { "audit": { "ignore-abandoned": { "acme/*": "Work scheduled for removal next month.", "acme/package": "Transitive dependency but unreachable and not in active use within our project context." } } } } ``` #### Simple format without reasons: ```json { "config": { "audit": { "ignore-abandoned": ["acme/*", "acme/package"] } } } ``` #### Detailed format with apply scope: The detailed format allows you to control whether an ignore applies to audit reports only, version blocking only, or both. The `apply` field accepts: - `audit` - Only ignore for audit reports (package doesn't appear in audit reports, but is still blocked during updates if [`block-abandoned`](https://getcomposer.org/doc/06-config.md.md#block-abandoned) is enabled) - `block` - Only ignore for version blocking (package can be used during updates even if [`block-abandoned`](https://getcomposer.org/doc/06-config.md.md#block-abandoned) is enabled, but still appears in audit reports) - `all` - Ignore for audit reports and version blocking (default behavior) ```json { "config": { "audit": { "ignore-abandoned": { "acme/package": { "apply": "block", "reason": "Allow during updates but still report as abandoned" }, "vendor/*": { "apply": "all", "reason": "We maintain these packages internally" } } } } } ``` All formats can be mixed together in the same configuration. ### ignore-severity > **Deprecated.** Use [`config.policy.advisories.ignore-severity`](https://getcomposer.org/doc/06-config.md.md#ignore-severity) instead. > Note: the new format uses `on-block`/`on-audit` booleans instead of `"apply": "audit|block|all"`. Defaults to `[]`. A list of severity levels that are ignored for audit reports and/or version blocking. #### Simple format: ```json { "config": { "audit": { "ignore-severity": ["low", "medium"] } } } ``` #### Detailed format with apply scope: The detailed format allows you to control whether an ignore applies to audit reports only, version blocking only, or both. The `apply` field accepts: - `audit` - Only ignore for audit reports (advisories with this severity don't appear in audit reports, but packages are still blocked during updates) - `block` - Only ignore for version blocking (packages can be used during updates, but advisories with this severity still appear in audit reports) - `all` - Ignore during both auditing and blocking (default behavior) ```json { "config": { "audit": { "ignore-severity": { "low": { "apply": "all" }, "medium": { "apply": "block" } } } } } ``` All formats can be mixed together in the same configuration. ### ignore-unreachable > **Deprecated.** Use [`config.policy.ignore-unreachable`](https://getcomposer.org/doc/06-config.md.md#ignore-unreachable) instead. Defaults to `false`. Should unreachable repositories be ignored during a `composer audit`. This can be helpful if you are running the command in an environment from which not all repositories can be accessed. This setting does not apply to version blocking or audit reports generated in other places than the `composer audit` command. ```json { "config": { "audit": { "ignore-unreachable": true } } } ``` ### block-insecure > **Deprecated.** Use [`config.policy.advisories.block`](https://getcomposer.org/doc/06-config.md.md#block) instead. Defaults to `true`. If `true`, any package versions affected by security advisories will be blocked and cannot be used during a composer update/require/delete commands, unless the security advisories are ignored. If [`block-abandoned`](https://getcomposer.org/doc/06-config.md.md#block-abandoned) is enabled, version blocking will also prevent use of abandoned packages. ```json { "config": { "audit": { "block-insecure": false } } } ``` ### block-abandoned > **Deprecated.** Use [`config.policy.abandoned.block`](https://getcomposer.org/doc/06-config.md.md#block-1) instead. Defaults to `false`. If `true`, any abandoned packages cannot be used during a composer update/required/delete command. Only applies if version blocking is not disabled by setting [`block-insecure`](https://getcomposer.org/doc/06-config.md.md#block-insecure) to false. ```json { "config": { "audit": { "block-abandoned": true } } } ``` ## use-parent-dir When running Composer in a directory where there is no composer.json, if there is one present in a directory above Composer will by default ask you whether you want to use that directory's composer.json instead. If you always want to answer yes to this prompt, you can set this config value to `true`. To never be prompted, set it to `false`. The default is `"prompt"`. > **Note:** This config must be set in your global user-wide config for it > to work. Use for example `php composer.phar config --global use-parent-dir true` > to set it. ## store-auths What to do after prompting for authentication, one of: `true` (always store), `false` (do not store) and `"prompt"` (ask every time), defaults to `"prompt"`. ## github-protocols Defaults to `["https", "ssh", "git"]`. A list of protocols to use when cloning from github.com, in priority order. By default `git` is present but only if [secure-http](https://getcomposer.org/doc/06-config.md.md#secure-http) is disabled, as the git protocol is not encrypted. If you want your origin remote push URLs to be using https and not ssh (`git@github.com:...`), then set the protocol list to be only `["https"]` and Composer will stop overwriting the push URL to an ssh URL. ## github-oauth A list of domain names and oauth keys. For example using `{"github.com": "oauthtoken"}` as the value of this option will use `oauthtoken` to access private repositories on github and to circumvent the low IP-based rate limiting of their API. Composer may prompt for credentials when needed, but these can also be manually set. Read more on how to get an OAuth token for GitHub and cli syntax [here](https://getcomposer.org/doc/articles/authentication-for-private-packages.md.md#github-oauth). ## gitlab-domains Defaults to `["gitlab.com"]`. A list of domains of GitLab servers. This is used if you use the `gitlab` repository type. ## gitlab-oauth A list of domain names and oauth keys. For example using `{"gitlab.com": "oauthtoken"}` as the value of this option will use `oauthtoken` to access private repositories on gitlab. Please note: If the package is not hosted at gitlab.com the domain names must be also specified with the [`gitlab-domains`](https://getcomposer.org/doc/06-config.md.md#gitlab-domains) option. Further info can also be found [here](https://getcomposer.org/doc/articles/authentication-for-private-packages.md.md#gitlab-oauth) ## gitlab-token A list of domain names and private tokens. Private token can be either simple string, or array with username and token. For example using `{"gitlab.com": "privatetoken"}` as the value of this option will use `privatetoken` to access private repositories on gitlab. Using `{"gitlab.com": {"username": "gitlabuser", "token": "privatetoken"}}` will use both username and token for gitlab deploy token functionality (https://docs.gitlab.com/ee/user/project/deploy_tokens/) Using `gitlab-ci-token` as the username instead stores a [GitLab CI job token](https://docs.gitlab.com/ci/jobs/ci_job_token/), which Composer sends as a `JOB-TOKEN` header (downloading dist archives from `vcs` repositories that way requires GitLab 19.3 or newer), except for GitLab's Composer package registry, which only accepts job tokens via HTTP basic auth with the `gitlab-ci-token` username, so Composer uses that there. Please note: If the package is not hosted at gitlab.com the domain names must be also specified with the [`gitlab-domains`](https://getcomposer.org/doc/06-config.md.md#gitlab-domains) option. The token must have `api` or `read_api` scope. Further info can also be found [here](https://getcomposer.org/doc/articles/authentication-for-private-packages.md.md#gitlab-token) ## gitlab-protocol A protocol to force use of when creating a repository URL for the `source` value of the package metadata. One of `git` or `http`. (`https` is treated as a synonym for `http`.) Helpful when working with projects referencing private repositories which will later be cloned in GitLab CI jobs with a [GitLab CI_JOB_TOKEN](https://docs.gitlab.com/ee/ci/variables/predefined_variables.html#predefined-variables-reference) using HTTP basic auth for the clone. By default, Composer will generate a git-over-SSH URL for private repositories and HTTP(S) only for public. ## forgejo-domains Defaults to `["codeberg.org"]`. A list of domains of Forgejo servers. This is used if you use the `forgejo` repository type. ## forgejo-token A list of domain names and username/access-tokens to authenticate against them. For example using `{"codeberg.org": {"username": "forgejo-user", "token": "access-token"}}` as the value of this option will let Composer authenticate against codeberg.org. Please note: If the package is not hosted at codeberg.org the domain names must be also specified with the [`forgejo-domains`](https://getcomposer.org/doc/06-config.md.md#forgejo-domains) option. Further info can also be found [here](https://getcomposer.org/doc/articles/authentication-for-private-packages.md.md#forgejo-token) ## disable-tls Defaults to `false`. If set to true all HTTPS URLs will be tried with HTTP instead and no network level encryption is performed. Enabling this is a security risk and is NOT recommended. The better way is to enable the php_openssl extension in php.ini. Enabling this will implicitly disable the `secure-http` option. ## secure-http Defaults to `true`. If set to true only HTTPS URLs are allowed to be downloaded via Composer. If you really absolutely need HTTP access to something then you can disable it, but using [Let's Encrypt](https://letsencrypt.org/) to get a free SSL certificate is generally a better alternative. ## bitbucket-oauth A list of domain names and consumers. For example using `{"bitbucket.org": {"consumer-key": "myKey", "consumer-secret": "mySecret"}}`. Read more [here](https://getcomposer.org/doc/articles/authentication-for-private-packages.md.md#bitbucket-oauth). ## cafile Location of Certificate Authority file on local filesystem. In PHP 5.6+ you should rather set this via openssl.cafile in php.ini, although PHP 5.6+ should be able to detect your system CA file automatically. ## capath If cafile is not specified or if the certificate is not found there, the directory pointed to by capath is searched for a suitable certificate. capath must be a correctly hashed certificate directory. ## http-basic A list of domain names and username/passwords to authenticate against them. For example using `{"example.org": {"username": "alice", "password": "foo"}}` as the value of this option will let Composer authenticate against example.org. More info can be found [here](https://getcomposer.org/doc/articles/authentication-for-private-packages.md.md#http-basic). ## bearer A list of domain names and tokens to authenticate against them. For example using `{"example.org": "foo"}` as the value of this option will let Composer authenticate against example.org using an `Authorization: Bearer foo` header. ## custom-headers A list of domain names and HTTP headers to send to them. For example using `{"example.org": ["API-TOKEN: foo", "X-Custom-Header: bar"]}` as the value of this option will send both headers with every request to example.org. Each header must be in the `Header-Name: Header-Value` format. More info can be found [here](https://getcomposer.org/doc/articles/authentication-for-private-packages.md.md#custom-headers). ## client-certificate A list of domain names and client TLS certificates to use for them. For example using `{"example.org": {"local_cert": "/path/to/cert.pem", "local_pk": "/path/to/key.pem", "passphrase": "foo"}}` as the value of this option will let Composer authenticate against example.org with that certificate. `local_cert` is required, `local_pk` and `passphrase` are optional. More info can be found [here](https://getcomposer.org/doc/articles/authentication-for-private-packages.md.md#client-tls-certificates). ## platform Lets you fake platform packages (PHP and extensions) so that you can emulate a production env or define your target platform in the config. Example: `{"php": "7.0.3", "ext-something": "4.0.3"}`. This will make sure that no package requiring more than PHP 7.0.3 can be installed regardless of the actual PHP version you run locally. However it also means the dependencies are not checked correctly anymore, if you run PHP 5.6 it will install fine as it assumes 7.0.3, but then it will fail at runtime. This also means if `{"php":"7.4"}` is specified; no packages will be used that define `7.4.1` as minimum. Therefore if you use this it is recommended, and safer, to also run the [`check-platform-reqs`](https://getcomposer.org/doc/03-cli.md.md#check-platform-reqs) command as part of your deployment strategy. If a dependency requires some extension that you do not have installed locally you may ignore it instead by passing `--ignore-platform-req=ext-foo` to `update`, `install` or `require`. In the long run though you should install required extensions as if you ignore one now and a new package you add a month later also requires it, you may introduce issues in production unknowingly. If you have an extension installed locally but *not* on production, you may want to artificially hide it from Composer using `{"ext-foo": false}`. ## vendor-dir Defaults to `vendor`. You can install dependencies into a different directory if you want to. `$HOME` and `~` will be replaced by your home directory's path in vendor-dir and all `*-dir` options below. ## bin-dir Defaults to `vendor/bin`. If a project includes binaries, they will be symlinked into this directory. ## data-dir Defaults to `C:\Users\\AppData\Roaming\Composer` on Windows, `$XDG_DATA_HOME/composer` on unix systems that follow the XDG Base Directory Specifications, and `$COMPOSER_HOME` on other unix systems. Right now it is only used for storing past composer.phar files to be able to roll back to older versions. See also [COMPOSER_HOME](https://getcomposer.org/doc/03-cli.md.md#composer_home). Because `self-update --rollback` restores a previously stored `composer.phar` from this directory, it must be writable only by the user that owns the Composer installation and should be treated as a trusted location. A directory writable by other users would let them plant a malicious phar that a privileged rollback would install. ## cache-dir Defaults to `C:\Users\\AppData\Local\Composer` on Windows, `/Users//Library/Caches/composer` on macOS, `$XDG_CACHE_HOME/composer` on unix systems that follow the XDG Base Directory Specifications, and `$COMPOSER_HOME/cache` on other unix systems. Stores all the caches used by Composer. See also [COMPOSER_HOME](https://getcomposer.org/doc/03-cli.md.md#composer_home), and [Caching Composer dependencies](https://getcomposer.org/doc/articles/caching.md.md) for caching it in CI. ## cache-files-dir Defaults to `$cache-dir/files`. Stores the zip archives of packages. ## cache-repo-dir Defaults to `$cache-dir/repo`. Stores repository metadata for the `composer` type and the VCS repos of type `svn`, `fossil`, `github` and `bitbucket`. ## cache-vcs-dir Defaults to `$cache-dir/vcs`. Stores VCS clones for loading VCS repository metadata for the `git`/`hg` types and to speed up installs. ## cache-ttl Defaults to `15552000` (6 months). The time-to-live (in seconds) applied to the repo and vcs caches when running `composer clear-cache --gc`, which is the only time those are garbage collected. Entries that have not been used for this long are removed. It is also used for the files cache unless [cache-files-ttl](https://getcomposer.org/doc/06-config.md.md#cache-files-ttl) is set. Setting it to 0 makes `composer clear-cache --gc` empty the repo and vcs caches, and disables the files cache unless [cache-files-ttl](https://getcomposer.org/doc/06-config.md.md#cache-files-ttl) is set. ## cache-files-ttl Defaults to the value of [cache-ttl](https://getcomposer.org/doc/06-config.md.md#cache-ttl), so `15552000` (6 months) unless that is changed. Composer caches all dist (zip, tar, ...) packages that it downloads. Those are purged after being unused for that long. This option allows you to tweak this duration (in seconds) or disable it completely by setting it to 0. ## cache-files-maxsize Defaults to `300MiB`. Composer caches all dist (zip, tar, ...) packages that it downloads. When the garbage collection is periodically ran, this is the maximum size the cache will be able to use. Older (less used) files will be removed first until the cache fits. ## cache-read-only Defaults to `false`. Whether to use the Composer cache in read-only mode. ## bin-compat Defaults to `auto`. Determines the compatibility of the binaries to be installed. If it is `auto` then Composer only installs .bat proxy files when on Windows or WSL. If set to `full` then both .bat files for Windows and scripts for Unix-based operating systems will be installed for each binary. This is mainly useful if you run Composer inside a linux VM but still want the `.bat` proxies available for use in the Windows host OS. If set to `proxy` Composer will only create bash/Unix-style proxy files and no .bat files even on Windows/WSL. ## prepend-autoloader Defaults to `true`. If `false`, the Composer autoloader will not be prepended to existing autoloaders. This is sometimes required to fix interoperability issues with other autoloaders. ## autoloader-suffix Defaults to `null`. When set to a non-empty string, this value will be used as a suffix for the generated Composer autoloader. If set to `null`, the `content-hash` value from the `composer.lock` file will be used if available; otherwise, a random suffix will be generated. ## optimize-autoloader Defaults to `false`. If `true`, always optimize when dumping the autoloader. ## strict-psr-autoloader Defaults to `false`. If `true`, `install` and `update` return a failed exit code (6), and `dump-autoload` returns a failed exit code (1), if PSR-4 or PSR-0 mapping errors are present in the current project (dependencies excluded). Requires `optimize-autoloader` or `classmap-authoritative` to be enabled to work. ## sort-packages Defaults to `false`. If `true`, the `require` command keeps packages sorted by name in `composer.json` when adding a new package. ## classmap-authoritative Defaults to `false`. If `true`, the Composer autoloader will only load classes from the classmap. Implies `optimize-autoloader`. ## apcu-autoloader Defaults to `false`. If `true`, the Composer autoloader will check for APCu and use it to cache found/not-found classes when the extension is enabled. ## github-domains Defaults to `["github.com"]`. A list of domains to use in github mode. This is used for GitHub Enterprise setups. ## github-expose-hostname Defaults to `true`. If `false`, the OAuth tokens created to access the github API will have a date instead of the machine hostname. ## use-github-api Defaults to `true`. Similar to the `no-api` key on a specific repository, setting `use-github-api` to `false` will define the global behavior for all GitHub repositories to clone the repository as it would with any other git repository instead of using the GitHub API. But unlike using the `git` driver directly, Composer will still attempt to use GitHub's zip files. ## notify-on-install Defaults to `true`. Composer allows repositories to define a notification URL, so that they get notified whenever a package from that repository is installed. This option allows you to disable that behavior. ## discard-changes Defaults to `false` and can be any of `true`, `false` or `"stash"`. This option allows you to set the default style of handling dirty updates when in non-interactive mode. `true` will always discard changes in vendors, while `"stash"` will try to stash and reapply. Use this for CI servers or deploy scripts if you tend to have modified vendors. ## archive-format Defaults to `tar`. Overrides the default format used by the archive command. ## archive-dir Defaults to `.`. Default destination for archives created by the archive command. Example: ```json { "config": { "archive-dir": "/home/user/.composer/repo" } } ``` ## htaccess-protect Defaults to `true`. If set to `false`, Composer will not create `.htaccess` files in the Composer home, cache, and data directories. ## lock Defaults to `true`. If set to `false`, Composer will not create a `composer.lock` file and will ignore it if one is present. ## platform-check Defaults to `php-only` which only checks the PHP version. Set to `true` to also check the presence of extension. If set to `false`, Composer will not create and require a `platform_check.php` file as part of the autoloader bootstrap. ## secure-svn-domains Defaults to `[]`. Lists domains which should be trusted/marked as using a secure Subversion/SVN transport. By default svn:// protocol is seen as insecure and will throw, but you can set this config option to `["example.org"]` to allow using svn URLs on that hostname. This is a better/safer alternative to disabling `secure-http` altogether. ## bump-after-update Defaults to `false` and can be any of `true`, `false`, `"dev"` or `"no-dev"`. If set to true, Composer will run the `bump` command after running the `update` command. If set to `"dev"` or `"no-dev"` then only the corresponding dependencies will be bumped. ## allow-missing-requirements Defaults to `false`. Ignores error during `install` if there are any missing requirements - the lock file is not up to date with the latest changes in `composer.json`. ## update-with-minimal-changes Defaults to `false`. If set to true, Composer will only perform absolutely necessary changes to transitive dependencies during update. Can also be set via the `COMPOSER_MINIMAL_CHANGES=1` env var. ← [Repositories](https://getcomposer.org/doc/05-repositories.md.md) | [Runtime](https://getcomposer.org/doc/07-runtime.md.md) → --- Source: https://getcomposer.org/doc/07-runtime.md # Runtime Composer utilities While Composer is mostly used around your project to install its dependencies, there are a few things which are made available to you at runtime. If you need to rely on some of these in a specific version, you can require the `composer-runtime-api` package. ## Autoload The autoloader is the most used one, and is already covered in our [basic usage guide](https://getcomposer.org/doc/01-basic-usage.md.md#autoloading). It is available in all Composer versions. ## Installed versions composer-runtime-api 2.0 introduced a new `Composer\InstalledVersions` class which offers a few static methods to inspect which versions are currently installed. This is automatically available to your code as long as you include the Composer autoloader. The main use cases for this class are the following: ### Knowing whether package X (or virtual package) is present ```php \Composer\InstalledVersions::isInstalled('vendor/package'); // returns bool \Composer\InstalledVersions::isInstalled('psr/log-implementation'); // returns bool ``` As of Composer 2.1, you may also check if something was installed via require-dev or not by passing false as second argument: ```php \Composer\InstalledVersions::isInstalled('vendor/package'); // returns true assuming this package is installed \Composer\InstalledVersions::isInstalled('vendor/package', false); // returns true if vendor/package is in require, false if in require-dev ``` Note that this can not be used to check whether platform packages are installed. ### Knowing whether package X is installed in version Y > **Note:** To use this, your package must require `"composer/semver": "^3.0"`. ```php use Composer\Semver\VersionParser; \Composer\InstalledVersions::satisfies(new VersionParser, 'vendor/package', '2.0.*'); \Composer\InstalledVersions::satisfies(new VersionParser, 'psr/log-implementation', '^1.0'); ``` This will return true if e.g. vendor/package is installed in a version matching `2.0.*`, but also if the given package name is replaced or provided by some other package. ### Knowing the version of package X > **Note:** This will return `null` if the package name you ask for is not itself installed > but merely provided or replaced by another package. We therefore recommend using satisfies() > in library code at least. In application code you have a bit more control and it is less > important. ```php // returns a normalized version (e.g. 1.2.3.0) if vendor/package is installed, // or null if it is provided/replaced, // or throws OutOfBoundsException if the package is not installed at all \Composer\InstalledVersions::getVersion('vendor/package'); ``` ```php // returns the original version (e.g. v1.2.3) if vendor/package is installed, // or null if it is provided/replaced, // or throws OutOfBoundsException if the package is not installed at all \Composer\InstalledVersions::getPrettyVersion('vendor/package'); ``` ```php // returns the package dist or source reference (e.g. a git commit hash) if vendor/package is installed, // or null if it is provided/replaced, // or throws OutOfBoundsException if the package is not installed at all \Composer\InstalledVersions::getReference('vendor/package'); ``` ### Knowing a package's own installed version If you are only interested in getting a package's own version, e.g. in the source of acme/foo you want to know which version acme/foo is currently running to display that to the user, then it is acceptable to use getVersion/getPrettyVersion/getReference. The warning in the section above does not apply in this case as you are sure the package is present and not being replaced if your code is running. It is nonetheless a good idea to make sure you handle the `null` return value as gracefully as possible for safety. ---- A few other methods are available for more complex usages, please refer to the source/docblocks of [the class itself](https://github.com/composer/composer/blob/main/src/Composer/InstalledVersions.php). ### Knowing the path in which a package is installed The `getInstallPath` method to retrieve a package's absolute install path. > **Note:** The path, while absolute, may contain `../` or symlinks. It is > not guaranteed to be equivalent to a `realpath()` so you should run a > realpath on it if that matters to you. ```php // returns an absolute path to the package installation location if vendor/package is installed, // or null if it is provided/replaced, or the package is a metapackage // or throws OutOfBoundsException if the package is not installed at all \Composer\InstalledVersions::getInstallPath('vendor/package'); ``` > Available as of Composer 2.1 (i.e. `composer-runtime-api ^2.1`) ### Knowing which packages of a given type are installed The `getInstalledPackagesByType` method accepts a package type (e.g. foo-plugin) and lists the packages of that type which are installed. You can then use the methods above to retrieve more information about each package if needed. This method should alleviate the need for custom installers placing plugins in a specific path instead of leaving them in the vendor dir. You can then find plugins to initialize at runtime via InstalledVersions, including their paths via getInstallPath if needed. ```php \Composer\InstalledVersions::getInstalledPackagesByType('foo-plugin'); ``` > Available as of Composer 2.1 (i.e. `composer-runtime-api ^2.1`) ## Platform check composer-runtime-api 2.0 introduced a new `vendor/composer/platform_check.php` file, which is included automatically when you include the Composer autoloader. It verifies that platform requirements (i.e. php and php extensions) are fulfilled by the PHP process currently running. If the requirements are not met, the script prints a warning with the missing requirements and exits with code 104. To avoid an unexpected white page of death with some obscure PHP extension warning in production, you can run `composer check-platform-reqs` as part of your deployment/build and if that returns a non-0 code you should abort. The default value is `php-only` which only checks the PHP version. If you for some reason do not want to use this safety check, and would rather risk runtime errors when your code executes, you can disable this by setting the [`platform-check`](https://getcomposer.org/doc/06-config.md.md#platform-check) config option to `false`. If you want the check to include verifying the presence of PHP extensions, set the config option to `true`. `ext-*` requirements will then be verified but for performance reasons Composer only checks the extension is present, not its exact version. `lib-*` requirements are never supported/checked by the platform check feature. ## Autoloader path in binaries composer-runtime-api 2.2 introduced a new `$_composer_autoload_path` global variable set when running binaries installed with Composer. Read more about this [on the vendor binaries docs](https://getcomposer.org/doc/articles/vendor-binaries.md.md#finding-the-composer-autoloader-from-a-binary). This is set by the binary proxy and as such is not made available to projects by Composer's `vendor/autoload.php`, which would be useless as it would point back to itself. ## Binary (bin-dir) path in binaries composer-runtime-api 2.2.2 introduced a new `$_composer_bin_dir` global variable set when running binaries installed with Composer. Read more about this [on the vendor binaries docs](https://getcomposer.org/doc/articles/vendor-binaries.md.md#finding-the-composer-bin-dir-from-a-binary). This is set by the binary proxy and as such is not made available to projects by Composer's `vendor/autoload.php`. ← [Config](https://getcomposer.org/doc/06-config.md.md) | [Community](https://getcomposer.org/doc/08-community.md.md) → --- Source: https://getcomposer.org/doc/08-community.md # Community There are many people using Composer already, and quite a few of them are contributing. ## Contributing If you would like to contribute to Composer, please read the [README](https://github.com/composer/composer) and [CONTRIBUTING](https://github.com/composer/composer/blob/main/.github/CONTRIBUTING.md) documents. The most important guidelines are described as follows: > All code contributions - including those of people having commit access - must > go through a pull request and approved by a core developer before being > merged. This is to ensure proper review of all the code. > > Fork the project, create a feature branch, and send us a pull request. > > To ensure a consistent code base, you should make sure the code follows > the [PSR-12 Coding Standards](https://www.php-fig.org/psr/psr-12/). ## Support The IRC channel is on irc.libera.chat: [#composer](ircs://irc.libera.chat:6697/composer). [Stack Overflow](https://stackoverflow.com/questions/tagged/composer-php) and [GitHub Discussions](https://github.com/composer/composer/discussions) both have a collection of Composer related questions. For paid support, we do provide Composer-related support via chat and email to [Private Packagist](https://packagist.com) customers. ← [Runtime](https://getcomposer.org/doc/07-runtime.md.md) --- Source: https://getcomposer.org/doc/articles/aliases.md # Aliases ## Why aliases? When you are using a VCS repository, you will only get comparable versions for branches that look like versions, such as `2.0` or `2.0.x`. For your `main` branch, you will get a `dev-main` version. For your `bugfix` branch, you will get a `dev-bugfix` version. If your `main` branch is used to tag releases of the `1.0` development line, i.e. `1.0.1`, `1.0.2`, `1.0.3`, etc., any package depending on it will probably require version `1.0.*`. If anyone wants to require the latest `dev-main`, they have a problem: Other packages may require `1.0.*`, so requiring that dev version will lead to conflicts, since `dev-main` does not match the `1.0.*` constraint. Enter aliases. ## Branch alias The `dev-main` branch is one in your main VCS repo. It is rather common that someone will want the latest main dev version. Thus, Composer allows you to alias your `dev-main` branch to a `1.0.x-dev` version. It is done by specifying a `branch-alias` field under `extra` in `composer.json`: ```json { "extra": { "branch-alias": { "dev-main": "1.0.x-dev" } } } ``` If you alias a non-comparable version (such as dev-develop) `dev-` must prefix the branch name. You may also alias a comparable version (i.e. start with numbers, and end with `.x-dev`), but only as a more specific version. For example, a `1.x` or `1.x-dev` branch could be aliased from `1.x-dev` to `1.2.x-dev` as that is more specific. The alias must be a comparable dev version (you cannot alias `dev-main` to `dev-master` for example), and the `branch-alias` must be present on the branch that it references. To alias `dev-main`, you need to define and commit it on the `main` branch. As a result, anyone can now require `1.0.*` and it will happily install `dev-main`. In order to use branch aliasing, you must own the repository of the package being aliased. If you want to alias a third party package without maintaining a fork of it, use inline aliases as described below. ## Require inline alias Branch aliases are great for aliasing main development lines. But in order to use them you need to have control over the source repository, and you need to commit changes to version control. This is not really fun when you want to try a bugfix of some library that is a dependency of your local project. For this reason, you can alias packages in your `require` and `require-dev` fields. Let's say you found a bug in the `monolog/monolog` package. You cloned [Monolog](https://github.com/Seldaek/monolog) on GitHub and fixed the issue in a branch named `bugfix`. Now you want to install that version of monolog in your local project. You are using `symfony/monolog-bundle` which requires `monolog/monolog` version `1.*`. So you need your `dev-bugfix` to match that constraint. Add this to your project's root `composer.json`: ```json { "repositories": [ { "type": "vcs", "url": "https://github.com/you/monolog" } ], "require": { "symfony/monolog-bundle": "2.0", "monolog/monolog": "dev-bugfix as 1.0.x-dev" } } ``` Or let Composer add it for you with: ```shell php composer.phar require "monolog/monolog:dev-bugfix as 1.0.x-dev" ``` That will fetch the `dev-bugfix` version of `monolog/monolog` from your GitHub and alias it to `1.0.x-dev`. > **Note:** Inline aliasing is a root-only feature. If a package with inline > aliases is required, the alias (right of the `as`) is used as the version > constraint. The part left of the `as` is discarded. As a consequence, if > A requires B and B requires `monolog/monolog` version `dev-bugfix as 1.0.x-dev`, > installing A will make B require `1.0.x-dev`, which may exist as a branch > alias or an actual `1.0` branch. If it does not, it must be > inline-aliased again in A's `composer.json`. > **Note:** Inline aliasing should be avoided, especially for published > packages/libraries. If you found a bug, try to get your fix merged upstream. > This helps to avoid issues for users of your package. --- Source: https://getcomposer.org/doc/articles/authentication-for-private-packages.md # Authentication for privately hosted packages and repositories Your [private package server](https://getcomposer.org/doc/articles/handling-private-packages.md.md) or version control system is probably secured with one or more authentication options. In order to allow your project to have access to these packages and repositories you will have to tell Composer how to authenticate with the server that hosts them. # Authentication principles Whenever Composer encounters a protected Composer repository it will try to authenticate using already defined credentials first. When none of those credentials apply it will prompt for credentials and save them (or a token if Composer is able to retrieve one). | type | Generated by Prompt? | |:---------------------------------------------------:|:--------------------:| | [http-basic](https://getcomposer.org/doc/articles/authentication-for-private-packages.md.md#http-basic) | yes | | [Inline http-basic](https://getcomposer.org/doc/articles/authentication-for-private-packages.md.md#inline-http-basic) | no | | [HTTP Bearer](https://getcomposer.org/doc/articles/authentication-for-private-packages.md.md#http-bearer) | no | | [Custom Headers](https://getcomposer.org/doc/articles/authentication-for-private-packages.md.md#custom-headers) | no | | [Inline Custom Headers](https://getcomposer.org/doc/articles/authentication-for-private-packages.md.md#inline-custom-headers) | no | | [gitlab-oauth](https://getcomposer.org/doc/articles/authentication-for-private-packages.md.md#gitlab-oauth) | yes | | [gitlab-token](https://getcomposer.org/doc/articles/authentication-for-private-packages.md.md#gitlab-token) | yes | | [github-oauth](https://getcomposer.org/doc/articles/authentication-for-private-packages.md.md#github-oauth) | yes | | [bitbucket-oauth](https://getcomposer.org/doc/articles/authentication-for-private-packages.md.md#bitbucket-oauth) | yes | | [Client TLS certificates](https://getcomposer.org/doc/articles/authentication-for-private-packages.md.md#client-tls-certificates) | no | | [forgejo-token](https://getcomposer.org/doc/articles/authentication-for-private-packages.md.md#forgejo-token) | yes | Sometimes automatic authentication is not possible, or you may want to predefine authentication credentials. Credentials can be stored on 4 different places; in an `auth.json` for the project, a global `auth.json`, in the `composer.json` itself or in the `COMPOSER_AUTH` environment variable. ## Authentication in auth.json per project In this authentication storage method, an `auth.json` file will be present in the same folder as the projects' `composer.json` file. You can either create and edit this file using the command line or manually edit or create it. > **Note: Make sure the `auth.json` file is in `.gitignore`** to avoid > leaking credentials into your git history. ## Global authentication credentials If you don't want to supply credentials for every project you work on, storing your credentials globally might be a better idea. These credentials are stored in a global `auth.json` in your Composer home directory. ### Command line global credential editing For all authentication methods it is possible to edit them using the command line; - [http-basic](https://getcomposer.org/doc/articles/authentication-for-private-packages.md.md#command-line-http-basic) - [Inline http-basic](https://getcomposer.org/doc/articles/authentication-for-private-packages.md.md#command-line-inline-http-basic) - [HTTP Bearer](https://getcomposer.org/doc/articles/authentication-for-private-packages.md.md#command-line-http-bearer-authentication) - [Custom Headers](https://getcomposer.org/doc/articles/authentication-for-private-packages.md.md#command-line-custom-headers) - [gitlab-oauth](https://getcomposer.org/doc/articles/authentication-for-private-packages.md.md#command-line-gitlab-oauth) - [gitlab-token](https://getcomposer.org/doc/articles/authentication-for-private-packages.md.md#command-line-gitlab-token) - [github-oauth](https://getcomposer.org/doc/articles/authentication-for-private-packages.md.md#command-line-github-oauth) - [bitbucket-oauth](https://getcomposer.org/doc/articles/authentication-for-private-packages.md.md#command-line-bitbucket-oauth) - [forgejo-token](https://getcomposer.org/doc/articles/authentication-for-private-packages.md.md#command-line-forgejo-token) ### Manually editing global authentication credentials > **Note:** It is not recommended to manually edit your authentication options as this might > result in invalid json. Instead preferably use [the command line](https://getcomposer.org/doc/articles/authentication-for-private-packages.md.md#command-line-global-credential-editing). To manually edit it, run: ```shell php composer.phar config --global --editor [--auth] ``` For specific authentication implementations, see their sections; - [http-basic](https://getcomposer.org/doc/articles/authentication-for-private-packages.md.md#manual-http-basic) - [Inline http-basic](https://getcomposer.org/doc/articles/authentication-for-private-packages.md.md#manual-inline-http-basic) - [HTTP Bearer](https://getcomposer.org/doc/articles/authentication-for-private-packages.md.md#manual-http-bearer-authentication) - [Custom Headers](https://getcomposer.org/doc/articles/authentication-for-private-packages.md.md#manual-custom-headers) - [Inline Custom Headers](https://getcomposer.org/doc/articles/authentication-for-private-packages.md.md#manual-inline-custom-headers) - [gitlab-oauth](https://getcomposer.org/doc/articles/authentication-for-private-packages.md.md#manual-gitlab-oauth) - [gitlab-token](https://getcomposer.org/doc/articles/authentication-for-private-packages.md.md#manual-gitlab-token) - [github-oauth](https://getcomposer.org/doc/articles/authentication-for-private-packages.md.md#manual-github-oauth) - [bitbucket-oauth](https://getcomposer.org/doc/articles/authentication-for-private-packages.md.md#manual-bitbucket-oauth) - [Client TLS certificates](https://getcomposer.org/doc/articles/authentication-for-private-packages.md.md#manual-client-certificates) - [forgejo-token](https://getcomposer.org/doc/articles/authentication-for-private-packages.md.md#manual-forgejo-token) Manually editing this file instead of using the command line may result in invalid json errors. To fix this you need to open the file in an editor and fix the error. To find the location of your global `auth.json`, execute: ```shell php composer.phar config --global home ``` The folder will contain your global `auth.json` if it exists. You can open this file in your favorite editor and fix the error. ## Authentication in composer.json file itself > **Note:** **This is not recommended** as these credentials are visible > to anyone who has access to the composer.json, either when it is shared through > a version control system like git or when an attacker gains (read) access to > your production server files. It is also possible to add credentials to a `composer.json` on a per-project basis in the `config` section or directly in the repository definition. ## Authentication using the COMPOSER_AUTH environment variable > **Note:** Using the command line environment variable method also has security implications. > These credentials will most likely be stored in memory, > and may be persisted to a file like `~/.bash_history` (linux) or `ConsoleHost_history.txt` > (PowerShell on Windows) when closing a session. The final option to supply Composer with credentials is to use the `COMPOSER_AUTH` environment variable. These variables can be either passed as command line variables or set in actual environment variables. Read more about the usage of this environment variable [here](https://getcomposer.org/doc/03-cli.md.md#composer_auth). # Authentication methods ## http-basic ### Command line http-basic ```shell php composer.phar config [--global] http-basic.repo.example.org username password ``` In the above command, the config key `http-basic.repo.example.org` consists of two parts: - `http-basic` is the authentication method. - `repo.example.org` is the repository host name, you should replace it with the host name of your repository. ### Manual http-basic ```shell php composer.phar config [--global] --editor --auth ``` ```json { "http-basic": { "example.org": { "username": "username", "password": "password" } } } ``` ## Inline http-basic For the inline http-basic authentication method the credentials are not stored in a separate `auth.json` in the project or globally, but in the `composer.json` or global configuration in the same place where the Composer repository definition is defined. Make sure that the username and password are encoded according to [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986#section-2.1) (2.1. Percent-Encoding). If the username e.g. is an email address it needs to be passed as `name%40example.com`. ### Command line inline http-basic ```shell php composer.phar config [--global] repositories.unique-name composer https://username:password@repo.example.org ``` ### Manual inline http-basic ```shell php composer.phar config [--global] --editor ``` ```json { "repositories": [ { "type": "composer", "url": "https://username:password@example.org" } ] } ``` ## HTTP Bearer ### Command line HTTP Bearer authentication ```shell php composer.phar config [--global] bearer.repo.example.org token ``` In the above command, the config key `bearer.repo.example.org` consists of two parts: - `bearer` is the authentication method. - `repo.example.org` is the repository host name, you should replace it with the host name of your repository. ### Manual HTTP Bearer authentication ```shell php composer.phar config [--global] --editor --auth ``` ```json { "bearer": { "example.org": "TOKEN" } } ``` ## custom-headers Use custom HTTP headers for authentication with private repositories that require header-based authentication. ### Command line custom-headers ```shell php composer.phar config [--global] custom-headers.repo.example.org "API-TOKEN: YOUR-API-TOKEN" "X-CUSTOM-HEADER: Value" ``` In the above command, the config key `custom-headers.repo.example.org` consists of two parts: - `custom-headers` is the authentication method. - `repo.example.org` is the repository host name, you should replace it with the host name of your repository. You can provide multiple custom headers as separate arguments. Each header must be in the standard HTTP header format `"Header-Name: Header-Value"`. ### Manual custom-headers ```shell php composer.phar config [--global] --editor --auth ``` ```json { "custom-headers": { "repo.example.org": [ "API-TOKEN: YOUR-API-TOKEN", "X-CUSTOM-HEADER: Value" ] } } ``` ## Inline custom-headers ### Manual inline custom-headers For the inline custom-headers authentication method, the custom headers are defined directly in your `composer.json` file as part of the repository configuration. ```shell php composer.phar config [--global] --editor ``` ```json { "repositories": [ { "type": "composer", "url": "https://repo.example.org", "options": { "http": { "header": [ "API-TOKEN: YOUR-API-TOKEN", "X-CUSTOM-HEADER: Value" ] } } } ] } ``` ## gitlab-oauth > **Note:** For the gitlab authentication to work on private gitlab instances, the > [`gitlab-domains`](https://getcomposer.org/doc/06-config.md.md#gitlab-domains) section should also contain the URL. ### Command line gitlab-oauth ```shell php composer.phar config [--global] gitlab-oauth.gitlab.example.org token ``` In the above command, the config key `gitlab-oauth.gitlab.example.org` consists of two parts: - `gitlab-oauth` is the authentication method. - `gitlab.example.org` is the host name of your GitLab instance, you should replace it with the host name of your GitLab instance or use `gitlab.com` if you don't have a self-hosted GitLab instance. ### Manual gitlab-oauth ```shell php composer.phar config [--global] --editor --auth ``` ```json { "gitlab-oauth": { "example.org": "token" } } ``` ## gitlab-token > **Note:** For the gitlab authentication to work on private gitlab instances, the > [`gitlab-domains`](https://getcomposer.org/doc/06-config.md.md#gitlab-domains) section should also contain the URL. To create a new access token, go to your [access tokens section on GitLab](https://gitlab.com/-/user_settings/personal_access_tokens) (or the equivalent URL on your private instance) and create a new token. See also [the GitLab access token documentation](https://docs.gitlab.com/ee/user/profile/personal_access_tokens.html#creating-a-personal-access-token) for more information. When creating a gitlab token manually, make sure it has either the `read_api` or `api` scope. ### Command line gitlab-token ```shell php composer.phar config [--global] gitlab-token.gitlab.example.org token ``` In the above command, the config key `gitlab-token.gitlab.example.org` consists of two parts: - `gitlab-token` is the authentication method. - `gitlab.example.org` is the host name of your GitLab instance, you should replace it with the host name of your GitLab instance or use `gitlab.com` if you don't have a self-hosted GitLab instance. ### Manual gitlab-token ```shell php composer.phar config [--global] --editor --auth ``` ```json { "gitlab-token": { "example.org": "token" } } ``` ### GitLab CI job tokens Inside a GitLab CI job you can authenticate with the ephemeral `CI_JOB_TOKEN` instead of a personal access token, by storing it with `gitlab-ci-token` as the username: ```shell php composer.phar config [--global] -- gitlab-token.gitlab.example.org gitlab-ci-token "${CI_JOB_TOKEN}" ``` Composer then sends the job token as a `JOB-TOKEN` header (downloading dist archives from `vcs` repositories that way requires GitLab 19.3 or newer), except for GitLab's Composer package registry, which only accepts job tokens via HTTP basic auth with the `gitlab-ci-token` username, so Composer uses that there. Note that the job token must be [allowed to access](https://docs.gitlab.com/ci/jobs/ci_job_token/#control-job-token-access-to-your-project) the projects it fetches packages from. ## github-oauth GitHub currently offers two types of access tokens: - [Fine-grained tokens](https://github.com/settings/personal-access-tokens) - [Tokens (classic)](https://github.com/settings/personal-access-tokens) These can be found in [Settings](https://github.com/settings/profile), at the very bottom of the left-side menu ([Developer options](https://github.com/settings/apps)). To create a new access token, head to your [token settings section on GitHub](https://github.com/settings/personal-access-tokens) and [generate a new token](https://github.com/settings/personal-access-tokens/new). Read more about [Personal Access Tokens](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/creating-a-personal-access-token). It is [recommended](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens#types-of-personal-access-tokens) to use fine-grained tokens, as you can have much tighter control over what can be accessed. Composer requires read-only access to repository metadata and contents. In most cases, a fine-grained token with read-only access to public repositories might be sufficient. Even without any additional permissions, these tokens [raise your API rate limits](https://docs.github.com/en/rest/using-the-rest-api/rate-limits-for-the-rest-api). Additional permissions will be necessary in the following cases: - You are using `vcs` type `repositories` entries in your `composer.json` file pointing to private repositories. - You are cloning `source` or downloading `dist` files for private repositories over HTTPS (and not over SSH, for example). In these cases, create a fine-grained token with read-only access to "contents". The token can be bound to either all of your or the organisation's repositories, or even scoped down to only selected repositories. As of November 2025, fine-grained tokens are limited in that you can only use them to access the private repositories of a single user _or_ a single organisation at once. You may want to check the [GitHub documentation](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens#fine-grained-personal-access-tokens-limitations) on details about that. If you need to work with repositories from different organisations, check if using directory-specific authentication configuration can meet your requirements. As a last option, a "classic" token with the `repo` scope will give broad access to all of your private repositories – including write permissions and much more. The [scopes documentation](https://docs.github.com/en/developers/apps/building-oauth-apps/scopes-for-oauth-apps) contains the complete list. Be careful when using this kind of token. Regardless of the type of token used, we recommend using tokens with a limited lifetime. This reduces the exposure in case the token is compromised. ### Command line github-oauth ```shell php composer.phar config [--global] github-oauth.github.com token ``` In the above command, the config key `github-oauth.github.com` consists of two parts: - `github-oauth` is the authentication method. - `github.com` is the host name for which this token applies. For GitHub you most likely do not need to change this. ### Manual github-oauth ```shell php composer.phar config [--global] --editor --auth ``` ```json { "github-oauth": { "github.com": "token" } } ``` ## bitbucket-oauth The Bitbucket driver uses OAuth to access your private repositories via the Bitbucket REST APIs, and you will need to create an OAuth consumer to use the driver, please refer to [Atlassian's Documentation](https://support.atlassian.com/bitbucket-cloud/docs/use-oauth-on-bitbucket-cloud/). You will need to fill the callback URL with something to satisfy Bitbucket, but the address does not need to go anywhere and is not used by Composer. The created consumer needs to have at least the "Repository > Read" permissions. ### Command line bitbucket-oauth ```shell php composer.phar config [--global] bitbucket-oauth.bitbucket.org consumer-key consumer-secret ``` In the above command, the config key `bitbucket-oauth.bitbucket.org` consists of two parts: - `bitbucket-oauth` is the authentication method. - `bitbucket.org` is the host name for which this token applies. Unless you have a private instance you don't need to change this. ### Manual bitbucket-oauth ```shell php composer.phar config [--global] --editor --auth ``` ```json { "bitbucket-oauth": { "bitbucket.org": { "consumer-key": "key", "consumer-secret": "secret" } } } ``` ### Bitbucket API tokens As an alternative to OAuth consumers, you can use Atlassian API tokens. Create a token with the `read:repository:bitbucket` scope in [your Atlassian account](https://id.atlassian.com/manage-profile/security/api-tokens). Once you have a token, configure it using HTTP Basic authentication with your Atlassian account email as the username and the token as the password: ```shell php composer.phar config [--global] http-basic.bitbucket.org your@email.com api-token ``` Or manually in `auth.json`: ```shell php composer.phar config [--global] --editor --auth ``` ```json { "http-basic": { "bitbucket.org": { "username": "your@email.com", "password": "api-token" } } } ``` ## Client TLS certificates Accessing private repositories that require client TLS certificates. For global/project-wide configuration see [Handling private packages: Security section](https://getcomposer.org/doc/articles/handling-private-packages.md.md#security). ### Manual client certificates ```shell php composer.phar config [--global] --editor --auth ``` ```json { "client-certificate": { "repo.example.org": { "local_cert": "/path/to/certificate", "local_pk": "/path/to/key", "passphrase": "MySecretPassword" } } } ``` Supported options are `local_cert` (required), `local_pk`, `passphrase`. More information for options can be found at [SSL context options](https://www.php.net/manual/en/context.ssl.php) Options could be omitted: - `local_pk`: in case of keeping certificate and private key in a single file; - `passphrase`: in case of passwordless private key. ## forgejo-token > **Note:** For the forge authentication to work on private Forgejo instances, the > [`forgejo-domains`](https://getcomposer.org/doc/06-config.md.md#forgejo-domains) section should also contain the domain. To create a new access token, go to your [applications section on Forgejo](https://codeberg.org/user/settings/applications) (or the equivalent URL on your private instance) and create a new access token. See also [the Forgejo access token documentation](https://docs.codeberg.org/advanced/access-token/) for more information. When creating a Forgejo access token, make sure it has the `read:repository` scope. ### Command line forgejo-token ```shell php composer.phar config [--global] forgejo-token.forgejo.example.org username access-token ``` In the above command, the config key `forgejo-token.forgejo.example.org` consists of two parts: - `forgejo-token` is the authentication method. - `forgejo.example.org` is the host name of your Forgejo instance, you should replace it with the host name of your Forgejo instance or use `codeberg.org` if you don't have a self-hosted Forgejo instance. ### Manual forgejo-token ```shell php composer.phar config [--global] --editor --auth ``` ```json { "forgejo-token": { "forgejo.example.org": { "username": "forgejo-user", "token": "access-token" } } } ``` --- Source: https://getcomposer.org/doc/articles/autoloader-optimization.md # Autoloader optimization By default, the Composer autoloader runs relatively fast. However, due to the way PSR-4 and PSR-0 autoloading rules are set up, it needs to check the filesystem before resolving a classname conclusively. This slows things down quite a bit, but it is convenient in development environments because when you add a new class it can immediately be discovered/used without having to rebuild the autoloader configuration. The problem however is in production you generally want things to happen as fast as possible, as you can rebuild the configuration every time you deploy and new classes do not appear at random between deploys. For this reason, Composer offers a few strategies to optimize the autoloader. > **Note:** You **should not** enable any of these optimizations in **development** as > they all will cause various problems when adding/removing classes. The performance > gains are not worth the trouble in a development setting. ## Optimization Level 1: Class map generation ### How to run it? There are a few options to enable this: - Set `"optimize-autoloader": true` inside the config key of composer.json - Call `install` or `update` with `-o` / `--optimize-autoloader` - Call `dump-autoload` with `-o` / `--optimize` ### What does it do? Class map generation essentially converts PSR-4/PSR-0 rules into classmap rules. This makes everything quite a bit faster as for known classes the class map returns instantly the path, and Composer can guarantee the class is in there so there is no filesystem check needed. On PHP 5.6+, the class map is also cached in opcache which improves the initialization time greatly. If you make sure opcache is enabled, then the class map should load almost instantly and then class loading is fast. ### Trade-offs There are no real trade-offs with this method. It should always be enabled in production. The only issue is it does not keep track of autoload misses (i.e. when it cannot find a given class), so those fall back to PSR-4 rules and can still result in slow filesystem checks. To solve this issue two Level 2 optimization options exist, and you can decide to enable either if you have a lot of class_exists checks that are done for classes that do not exist in your project. ## Optimization Level 2/A: Authoritative class maps ### How to run it? There are a few options to enable this: - Set `"classmap-authoritative": true` inside the config key of composer.json - Call `install` or `update` with `-a` / `--classmap-authoritative` - Call `dump-autoload` with `-a` / `--classmap-authoritative` ### What does it do? Enabling this automatically enables Level 1 class map optimizations. This option says that if something is not found in the classmap, then it does not exist and the autoloader should not attempt to look on the filesystem according to PSR-4 rules. ### Trade-offs This option makes the autoloader always return very quickly. On the flipside it also means that in case a class is generated at runtime for some reason, it will not be allowed to be autoloaded. If your project or any of your dependencies does that then you might experience "class not found" issues in production. Enable this with care. > Note: This cannot be combined with Level 2/B optimizations. You have to choose one as > they address the same issue in different ways. ## Optimization Level 2/B: APCu cache ### How to run it? There are a few options to enable this: - Set `"apcu-autoloader": true` inside the config key of composer.json - Call `install` or `update` with `--apcu-autoloader` - Call `dump-autoload` with `--apcu` ### What does it do? This option adds an APCu cache as a fallback for the class map. It will not automatically generate the class map though, so you should still enable Level 1 optimizations manually if you so desire. Whether a class is found or not, that fact is always cached in APCu, so it can be returned quickly on the next request. ### Trade-offs This option requires APCu which may or may not be available to you. It also uses APCu memory for autoloading purposes, but it is safe to use and cannot result in classes not being found like the authoritative class map optimization above. > Note: This cannot be combined with Level 2/A optimizations. You have to choose one as > they address the same issue in different ways. --- Source: https://getcomposer.org/doc/articles/caching.md # Caching Composer dependencies Composer keeps a cache of everything it downloads on the machine it runs on, so that later runs on the same machine do not have to download it again. CI jobs and container builds usually start on a fresh machine or in a fresh container though, so this cache is empty at the start of every build unless you persist it between builds, for example with your CI provider's cache feature or a Docker BuildKit cache mount. This article explains which parts of Composer's cache are worth persisting between builds and how to do so safely. Two kinds of cache are involved: - the **Composer cache**: the directory in which Composer itself stores downloaded files, see [`cache-dir`](https://getcomposer.org/doc/06-config.md.md#cache-dir); - the **CI cache**: a feature of your CI provider that saves a directory at the end of a job under a **cache key**, and restores it at the start of a later job that asks for the same (or a matching) key. Persisting the Composer cache between builds should remain an optimization: a build must still produce the same result when the cache is empty. For most projects, persist the Composer cache rather than the installed `vendor/` directory. Composer can then reuse previously downloaded package archives instead of downloading them again, while `composer install` still installs exactly the versions `composer.lock` specifies and still checks that the PHP version and extensions of the build environment satisfy the requirements of those packages. ## What to cache The Composer cache consists of several parts, each stored in its own subdirectory of the cache directory. You can print the location of the cache directory on the current machine with: ```sh composer config cache-dir --absolute ``` The parts are: - the **files cache** ([`cache-files-dir`](https://getcomposer.org/doc/06-config.md.md#cache-files-dir)), which stores the dist archives (zip, tar, ...) of packages Composer has downloaded; - the **repository metadata cache** ([`cache-repo-dir`](https://getcomposer.org/doc/06-config.md.md#cache-repo-dir)), which stores the package metadata Composer fetched from repositories like Packagist.org to resolve dependencies; - the **VCS cache** ([`cache-vcs-dir`](https://getcomposer.org/doc/06-config.md.md#cache-vcs-dir)), which stores clones of VCS repositories, used to read metadata from `vcs` repositories and to install packages from source. The files cache is the part that saves the most time when persisted between builds, because `composer install` extracts every package from its dist archive, and the archives for a given `composer.lock` are the same in every build. Composer automatically removes old entries from the files cache: archives unused for six months are deleted, and the files cache is limited to 300 MiB, see [`cache-files-ttl`](https://getcomposer.org/doc/06-config.md.md#cache-files-ttl) and [`cache-files-maxsize`](https://getcomposer.org/doc/06-config.md.md#cache-files-maxsize). The repository metadata cache and the VCS cache are only cleaned up when you run `composer clear-cache --gc`, which you can do before the CI cache is saved to keep it from growing indefinitely. The CI examples below persist the entire Composer cache directory, because that is the simplest setup. A job that only runs `composer install` with a `composer.lock` mainly reads from the files cache (and the VCS cache for packages installed from source), so if CI cache storage is limited you can persist only `cache-files-dir`. A job that runs `composer update` also benefits from the repository metadata cache, because Composer then has to load package metadata to resolve dependencies. Many CI providers can only save directories inside the job's working directory, while Composer's default cache directory is in the user's home directory. You can set the `COMPOSER_CACHE_DIR` environment variable to move the Composer cache into the working directory, so the CI cache can save it from a known path: ```sh COMPOSER_CACHE_DIR="$PWD/.composer-cache" composer install --no-interaction --prefer-dist ``` Add such a cache directory inside your project to `.gitignore`, and to `.dockerignore` if you build images from the same checkout, so it does not show up as an untracked change or ends up in archives, Docker build contexts and code-analysis runs. A CI cache is usually shared between jobs, and often between branches, so do not add credentials, `auth.json`, SSH keys, tokens, or other secrets to the paths it saves. In particular, persist the Composer cache directory rather than the whole [`COMPOSER_HOME`](https://getcomposer.org/doc/03-cli.md.md#composer_home) directory, which can contain `auth.json`. ## Cache downloads, not installed dependencies Persisting `vendor/` in the CI cache can be tempting because restoring it lets you skip `composer install`, but it is often not faster: `vendor/` usually contains many small files, and on most CI systems saving and restoring many small files takes longer than saving and restoring the few larger archives in the Composer cache. A restored `vendor/` can also easily differ from what a fresh install in the current job would produce. Its contents depend on more than `composer.lock`: on install flags such as `--no-dev` or `--optimize-autoloader`, on files generated by Composer plugins or scripts, and on any changes made to files inside `vendor/`, which `composer install` does not detect or undo. A restored Composer cache cannot cause these problems: it only supplies downloaded archives, and Composer still reads `composer.lock`, checks the platform requirements, and installs every package into `vendor/` as it would without the cache. This makes persisting the Composer cache a good default. Persist `vendor/` only when every job restoring it uses the same install flags, PHP version and PHP extensions, and you include all of these in the cache key. Applications should always commit `composer.lock` to version control and run `composer install` in CI. A restored Composer cache should only make that install faster by avoiding downloads, not replace it. ## Cache keys A CI cache stores each saved directory as an entry under a cache key, and restores the entry whose key matches the key a later job requests. A good key keeps builds from restoring an entry created by an incompatible build environment, while still letting builds reuse entries created before a dependency change. Dist archives in the files cache are the same regardless of the PHP version or operating system they were downloaded on, so all jobs of a project, such as the jobs of a PHP version matrix, can usually share one Composer cache entry. When persisting the Composer cache, configure fallback keys (called `restore-keys` on GitHub Actions and `fallback_keys` on GitLab), so that when no entry matches the key of a changed `composer.lock`, the CI cache restores the most recent entry of an earlier `composer.lock` instead. Most archives will still be the same, so Composer only needs to download the packages that changed. When persisting `vendor/`, do not use fallback keys, and include the hash of `composer.lock`, the install flags, the PHP version, and the list of enabled PHP extensions in the key. `composer install` checks the platform requirements of the locked packages against the PHP version and extensions (unless you use `--ignore-platform-reqs`), and a `vendor/` restored from a different environment would skip that check. CI jobs running `composer update`, such as library jobs testing against the latest dependency versions, need a different approach. A key based on the hash of `composer.lock` is then the same in every run, because it is computed from the committed file (or from no file at all) rather than the versions that get installed. Most CI providers do not overwrite an existing entry, so the Composer cache is saved once and never updated with newer package versions. Instead, build the key from the hash of `composer.json` plus a value that is different on every run, and use prefixes of that key as fallback keys, so every run restores the most recent entry and saves a new one. On GitHub Actions for example: ```yaml key: composer-${{ hashFiles('composer.json') }}-${{ github.run_id }} restore-keys: | composer-${{ hashFiles('composer.json') }}- composer- ``` Some CI providers let jobs for pull requests from untrusted contributors, such as forks, save CI cache entries that jobs on trusted branches later restore. Such a job could save a Composer cache containing modified package archives, which a later trusted build would then install. Do not let untrusted jobs save cache entries that trusted jobs restore, following your CI provider's security documentation, and never put secrets in a CI cache. ## GitHub Actions For most workflows, [ramsey/composer-install](https://github.com/ramsey/composer-install) is the simplest option. It runs `composer install` and persists the Composer cache directory in the CI cache by default, so you usually do not need a separate caching step or a custom `COMPOSER_CACHE_DIR`: ```yaml - uses: shivammathur/setup-php@v2 with: php-version: ${{ matrix.php }} - uses: ramsey/composer-install@v4 ``` If you need explicit control over the cached path or the key, use `actions/cache` directly. The following example moves the Composer cache into the workspace, saves it under a key based on `composer.lock`, and restores the most recent entry starting with `composer-` when no entry matches the current `composer.lock`: ```yaml jobs: tests: runs-on: ubuntu-latest env: COMPOSER_CACHE_DIR: ${{ github.workspace }}/.composer-cache steps: - uses: actions/checkout@v7 - uses: actions/cache@v6 with: path: .composer-cache key: composer-${{ hashFiles('composer.lock') }} restore-keys: | composer- - name: Install dependencies run: composer install --no-interaction --prefer-dist --no-progress ``` Setting `COMPOSER_CACHE_DIR` on the job rather than on a single step makes every Composer command in the job use the persisted directory. When a workflow runs for pull requests from forks, follow GitHub Actions' cache-security guidance, see [Cache keys](https://getcomposer.org/doc/articles/caching.md.md#cache-keys), so that these jobs cannot save cache entries that jobs on trusted branches later restore. ## GitLab CI/CD GitLab can compute the cache key from the contents of `composer.lock`. GitLab only caches paths inside the project directory, so the example moves the Composer cache there: ```yaml variables: COMPOSER_CACHE_DIR: "$CI_PROJECT_DIR/.composer-cache" default: cache: key: files: - composer.lock paths: - .composer-cache/ before_script: - composer install --no-interaction --prefer-dist --no-progress ``` With this key, a changed `composer.lock` starts with an empty Composer cache. To reuse the archives of an earlier `composer.lock`, use a key that does not change with `composer.lock`, or list older keys in `cache:fallback_keys`. If the project has no `composer.lock`, GitLab uses the key `default`, which never changes, see [Cache keys](https://getcomposer.org/doc/articles/caching.md.md#cache-keys) for an alternative. ## Bitbucket Pipelines Bitbucket Pipelines provides a predefined `composer` cache. It always saves `~/.composer/cache`, but Composer uses a different cache directory in many environments, for example `/tmp/cache` in the official `composer` Docker image or `~/.cache/composer` on systems following the XDG specification. Set `COMPOSER_CACHE_DIR` to `~/.composer/cache`, otherwise Bitbucket saves an empty directory and Composer downloads everything again in every build, without any error: ```yaml pipelines: default: - step: caches: - composer script: - export COMPOSER_CACHE_DIR="$HOME/.composer/cache" - composer install --no-interaction --prefer-dist --no-progress ``` Once saved, a predefined cache entry is not updated, and it is only deleted after a week without use, so packages added to `composer.lock` in the meantime are downloaded in every build. Define a custom cache with a key based on `composer.lock` when you want a new entry saved whenever dependencies change, or when you need a different path. ## CircleCI CircleCI cache entries are immutable: once an entry is saved under a key, it is never updated. Include the checksum of `composer.lock` in the key, so a new entry is saved when dependencies change. Restore the cache before running Composer and save it afterwards. The example moves the Composer cache into the working directory, so the same relative path can be used in `save_cache`: ```yaml steps: - checkout - restore_cache: keys: - composer-v1-{{ checksum "composer.lock" }} - composer-v1- - run: name: Install dependencies command: | export COMPOSER_CACHE_DIR="$PWD/.composer-cache" composer install --no-interaction --prefer-dist --no-progress - save_cache: key: composer-v1-{{ checksum "composer.lock" }} paths: - .composer-cache ``` To discard all previously saved entries, for example after a corrupted cache, change the `v1` in the key prefix to `v2` in both places. ## Docker and BuildKit In Docker builds, a BuildKit cache mount lets the Composer cache persist from one build to the next, without being copied into the resulting image: ```dockerfile # syntax=docker/dockerfile:1 FROM php:8.4-cli RUN apt-get update && apt-get install -y --no-install-recommends git unzip \ && rm -rf /var/lib/apt/lists/* WORKDIR /app COPY . . RUN --mount=type=bind,from=composer/composer:2-bin,source=/composer,target=/usr/bin/composer \ --mount=type=cache,target=/tmp/composer-cache \ COMPOSER_CACHE_DIR=/tmp/composer-cache \ composer install --no-interaction --prefer-dist --no-progress ``` Run `composer install` in an image with the same PHP version and extensions as the image your application runs in. This example does so by installing in the application image itself and mounting the Composer binary from the [`composer/composer:2-bin` image](https://getcomposer.org/doc/00-intro.md.md#docker-image) only for the duration of the install step, so the Composer binary does not end up in the resulting image. Do not run the install in the full `composer` or `composer/composer` images instead: they ship the latest PHP version with only a few extensions, so `composer install` would fail its platform requirement checks for many projects, or produce a `vendor/` directory meant for a different PHP environment than the one your application runs in. BuildKit keeps cache mounts on the builder that ran the build. They are not included in exported build caches such as `--cache-to`, so on CI runners that start fresh for every job the cache mount is empty in every build, unless you use a persistent builder or a tool that saves and restores cache mounts, like [buildkit-cache-dance](https://github.com/reproducible-containers/buildkit-cache-dance). Exclude `vendor/` and any Composer cache directory inside your project in `.dockerignore`, so `COPY . .` does not copy them into the image. Independently of the Composer cache, Docker reuses the result of a build step (a layer) as long as the files copied before it did not change. With `COPY . .` before `composer install`, any change to your application's source therefore reruns the install. If your Composer scripts and plugins do not need the application source, you can copy only `composer.json` and `composer.lock` first, install, and copy the rest of the source afterwards, so the install step is only rerun when dependencies change. As the autoloader cannot be generated before the source is copied, generate it in a separate step: ```dockerfile COPY composer.json composer.lock ./ RUN --mount=type=bind,from=composer/composer:2-bin,source=/composer,target=/usr/bin/composer \ --mount=type=cache,target=/tmp/composer-cache \ COMPOSER_CACHE_DIR=/tmp/composer-cache \ composer install --no-interaction --prefer-dist --no-progress --no-autoloader COPY . . RUN --mount=type=bind,from=composer/composer:2-bin,source=/composer,target=/usr/bin/composer \ composer dump-autoload --optimize ``` Every `RUN` step that calls `composer`, like the `composer dump-autoload` step above, needs the bind mount, because the Composer binary is only available while it is mounted. If your scripts or plugins do need application files, keep copying the full source before `composer install`. Do not disable scripts or plugins with `--no-scripts` or `--no-plugins` only to get more layer reuse, as the resulting `vendor/` directory would be missing whatever they generate. ## Diagnosing cache problems When a build that restored a cache behaves differently from a build without one, first run it again without restoring the cache, for example by changing the cache key, to find out whether the cache is the cause at all. Locally, you can find and empty the Composer cache with these commands: ```sh composer config cache-dir --absolute composer clear-cache ``` In CI, also check which key the restored entry was saved under, and which job, branch and build environment saved it. A restored `vendor/` directory is most commonly stale because the key did not account for install flags, files generated by Composer plugins or scripts, or files modified inside `vendor/`. A reliable cache setup has three properties: the build still works when no cache entry is restored, a restored entry never supplies secrets, and the key prevents a build from restoring a `vendor/` directory installed for a different build environment. ## Further reading - [Composer configuration: cache settings](https://getcomposer.org/doc/06-config.md.md#cache-dir) - [Composer CLI: `clear-cache`](https://getcomposer.org/doc/03-cli.md.md#clear-cache--clearcache--cc) - [GitHub Actions dependency caching](https://docs.github.com/actions/reference/workflows-and-actions/dependency-caching) - [ramsey/composer-install](https://github.com/ramsey/composer-install) - [GitLab CI/CD cache examples](https://docs.gitlab.com/ci/caching/examples/) - [Bitbucket Pipelines dependency caches](https://support.atlassian.com/bitbucket-cloud/docs/cache-dependencies/) - [CircleCI dependency caching](https://circleci.com/docs/guides/optimize/caching/) --- Source: https://getcomposer.org/doc/articles/composer-platform-dependencies.md # Composer platform dependencies ## What are platform dependencies Composer makes information about the environment Composer runs in available as virtual packages. This allows other packages to define dependencies ([require](https://getcomposer.org/doc/04-schema.md.md#require), [conflict](https://getcomposer.org/doc/04-schema.md.md#conflict), [provide](https://getcomposer.org/doc/04-schema.md.md#provide), [replace](https://getcomposer.org/doc/04-schema.md.md#replace)) on different aspects of the platform, like PHP, extensions or system libraries, including version constraints. When you require one of the platform packages no code is installed. The version numbers of platform packages are derived from the environment Composer is executed in and they cannot be updated or removed. They can however be overwritten for the purposes of dependency resolution with a [platform configuration](https://getcomposer.org/doc/06-config.md.md#platform). **For example:** If you are executing `composer update` with a PHP interpreter in version `7.4.42`, then Composer automatically adds a package to the pool of available packages called `php` and assigns version `7.4.42` to it. That's how packages can add a dependency on the used PHP version: ```json { "require": { "php": ">=7.4" } } ``` Composer will check this requirement against the currently used PHP version when running the composer command. ### Different types of platform packages The following types of platform packages exist and can be depended on: 1. PHP (`php` and the subtypes: `php-64bit`, `php-ipv6`, `php-zts` `php-debug`) 2. PHP Extensions (`ext-*`, e.g. `ext-mbstring`) 3. PHP Libraries (`lib-*`, e.g. `lib-curl`) 4. Composer (`composer`, `composer-plugin-api`, `composer-runtime-api`) To see the complete list of platform packages available in your environment you can run `php composer.phar show --platform` (or `show -p` for short). The differences between the various Composer platform packages are explained further in this document. ## Plugin package `composer-plugin-api` You can modify Composer's behavior with [plugin](https://getcomposer.org/doc/articles/plugins.md.md) packages. Composer provides a set of versioned APIs for plugins. Because internal Composer changes may **not** change the plugin APIs, the API version may not increase every time the Composer version increases. E.g. In Composer version `2.3.12`, the `composer-plugin-api` version could still be `2.2.0`. ## Runtime package `composer-runtime-api` When applications which were installed with Composer are run (either on CLI or through a web request), they require the `vendor/autoload.php` file, typically as one of the first lines of executed code. Invocations of the Composer autoloader are considered the application "runtime". Starting with version 2.0, Composer makes [additional features](https://getcomposer.org/doc/07-runtime.md.md) (besides registering the class autoloader) available to the application runtime environment. Similar to `composer-plugin-api`, not every Composer release adds new runtime features, thus the version of `composer-runtime-api` is also increased independently from Composer's version. ## Composer package `composer` Starting with Composer 2.2.0, a new platform package called `composer` is available, which represents the exact Composer version that is executed. Packages depending on this platform package can therefore depend on (or conflict with) individual Composer versions to cover edge cases where neither the `composer-runtime-api` version nor the `composer-plugin-api` was changed. Because this option was introduced with Composer 2.2.0, it is recommended to add a `composer-plugin-api` dependency on at least `>=2.2.0` to provide a more meaningful error message for users running older Composer versions. In general, depending on `composer-plugin-api` or `composer-runtime-api` is always recommended over depending on concrete Composer versions with the `composer` platform package. --- Source: https://getcomposer.org/doc/articles/custom-installers.md # Setting up and using custom installers ## Synopsis At times, it may be necessary for a package to require additional actions during installation, such as installing packages outside of the default `vendor` library. In these cases you could consider creating a Custom Installer to handle your specific logic. ## Alternative to custom installers with Composer 2.1+ As of Composer 2.1, the `Composer\InstalledVersions` class has a [`getInstalledPackagesByType`](https://getcomposer.org/doc/07-runtime.md.md#knowing-which-packages-of-a-given-type-are-installed) method which can let you figure out at runtime which plugins/modules/extensions are installed. It is highly recommended to use that instead of building new custom installers if you are building a new application. This has the advantage of leaving all vendor code in the vendor directory, and not requiring custom installer code. ## Calling a Custom Installer Suppose that your project already has a Custom Installer for specific modules then invoking that installer is a matter of defining the correct [type][1] in your package file. > _See the next chapter for an instruction how to create Custom Installers._ Every Custom Installer defines which [type][1] string it will recognize. Once recognized it will completely override the default installer and only apply its own logic. An example use-case would be: > phpDocumentor features Templates that need to be installed outside of the > default /vendor folder structure. As such they have chosen to adopt the > `phpdocumentor-template` [type][1] and create a plugin providing the Custom > Installer to send these templates to the correct folder. An example composer.json of such a template package would be: ```json { "name": "phpdocumentor/template-responsive", "type": "phpdocumentor-template", "require": { "phpdocumentor/template-installer-plugin": "*" } } ``` > **IMPORTANT**: to make sure that the template installer is present at the > time the template package is installed, template packages should require > the plugin package. ## Creating an Installer A Custom Installer is defined as a class that implements the [`Composer\Installer\InstallerInterface`][4] and is usually distributed in a Composer Plugin. A basic Installer Plugin would thus compose of three files: 1. the package file: composer.json 2. The Plugin class, e.g.: `My\Project\Composer\Plugin.php`, containing a class that implements `Composer\Plugin\PluginInterface`. 3. The Installer class, e.g.: `My\Project\Composer\Installer.php`, containing a class that implements `Composer\Installer\InstallerInterface`. ### composer.json The package file is the same as any other package file but with the following requirements: 1. the [type][1] attribute must be `composer-plugin`. 2. the [extra][2] attribute must contain an element `class` defining the class name of the plugin (including namespace). If a package contains multiple plugins, this can be an array of class names. Example: ```json { "name": "phpdocumentor/template-installer-plugin", "type": "composer-plugin", "license": "MIT", "autoload": { "psr-0": {"phpDocumentor\\Composer": "src/"} }, "extra": { "class": "phpDocumentor\\Composer\\TemplateInstallerPlugin" }, "require": { "composer-plugin-api": "^1.0" }, "require-dev": { "composer/composer": "^1.3" } } ``` The example above has Composer itself in its require-dev, which allows you to use the Composer classes in your test suite for example. ### The Plugin class The class defining the Composer plugin must implement the [`Composer\Plugin\PluginInterface`][3]. It can then register the Custom Installer in its `activate()` method. The class may be placed in any location and have any name, as long as it is autoloadable and matches the `extra.class` element in the package definition. Example: ```php getInstallationManager()->addInstaller($installer); } } ``` ### The Custom Installer class The class that executes the custom installation should implement the [`Composer\Installer\InstallerInterface`][4] (or extend another installer that implements that interface). It defines the [type][1] string as it will be recognized by packages that will use this installer in the `supports()` method. > **NOTE**: _choose your [type][1] name carefully, it is recommended to follow > the format: `vendor-type`_. For example: `phpdocumentor-template`. The InstallerInterface class defines the following methods (please see the source for the exact signature): * **supports()**, here you test whether the passed [type][1] matches the name that you declared for this installer (see the example). * **isInstalled()**, determines whether a supported package is installed or not. * **install()**, here you can determine the actions that need to be executed upon installation. * **update()**, here you define the behavior that is required when Composer is invoked with the update argument. * **uninstall()**, here you can determine the actions that need to be executed when the package needs to be removed. * **getInstallPath()**, this method should return the absolute path where the package is to be installed. The path _must not end with a slash._ Example: ```php getPrettyName(), 0, 23); if ('phpdocumentor/template-' !== $prefix) { throw new \InvalidArgumentException( 'Unable to install template, phpdocumentor templates ' .'should always start their package name with ' .'"phpdocumentor/template-"' ); } return 'data/templates/'.substr($package->getPrettyName(), 23); } /** * @inheritDoc */ public function supports($packageType) { return 'phpdocumentor-template' === $packageType; } } ``` The example demonstrates that it is possible to extend the [`Composer\Installer\LibraryInstaller`][5] class to strip a prefix (`phpdocumentor/template-`) and use the remaining part to assemble a completely different installation path. > _Instead of being installed in `/vendor` any package installed using this > Installer will be put in the `/data/templates/` folder._ [1]: https://getcomposer.org/doc/04-schema.md.md#type [2]: https://getcomposer.org/doc/04-schema.md.md#extra [3]: https://github.com/composer/composer/blob/main/src/Composer/Plugin/PluginInterface.php [4]: https://github.com/composer/composer/blob/main/src/Composer/Installer/InstallerInterface.php [5]: https://github.com/composer/composer/blob/main/src/Composer/Installer/LibraryInstaller.php --- Source: https://getcomposer.org/doc/articles/handling-private-packages.md # Handling private packages # Private Packagist [Private Packagist](https://packagist.com) is a commercial package hosting product offering professional support and web based management of private and public packages, and granular access permissions. Private Packagist provides mirroring for packages' zip files which makes installs faster and independent from third party systems - e.g. you can deploy even if GitHub is down because your zip files are mirrored. Private Packagist is available as a hosted SaaS solution or as an on-premise self-hosted package, providing an interactive set up experience. Some of Private Packagist's revenue is used to pay for Composer and Packagist.org development and hosting so using it is a good way to support the maintenance of these open source projects financially. You can find more information about how to set up your own package archive on [Packagist.com](https://packagist.com). # Satis Satis on the other hand is open source but only a static `composer` repository generator. It is a bit like an ultra-lightweight, static file-based version of packagist and can be used to host the metadata of your company's private packages, or your own. You can install it using [Composer](https://github.com/composer/satis?tab=readme-ov-file#run-from-source) or [Docker](https://github.com/composer/satis?tab=readme-ov-file#run-as-docker-container). ## Setup For example let's assume you have a few packages you want to reuse across your company but don't really want to open-source. You would first define a Satis configuration: a json file that lists your curated [repositories](https://getcomposer.org/doc/05-repositories.md.md). The default file name is satis.json but it could be anything you like. Here is an example configuration, you see that it holds a few VCS repositories, but those could be any types of [repositories](https://getcomposer.org/doc/05-repositories.md.md). Then it uses `"require-all": true` which selects all versions of all packages in the repositories you defined. The default file Satis looks for is `satis.json` in the root of the repository. ```json { "name": "my/repository", "homepage": "http://packages.example.org", "repositories": [ { "type": "vcs", "url": "https://github.com/mycompany/privaterepo" }, { "type": "vcs", "url": "http://svn.example.org/private/repo" }, { "type": "vcs", "url": "https://github.com/mycompany/privaterepo2" } ], "require-all": true } ``` If you want to cherry pick which packages you want, you can list all the packages you want to have in your satis repository inside the classic composer `require` key, using a `"*"` constraint to make sure all versions are selected, or another constraint if you want really specific versions. ```json { "repositories": [ { "type": "vcs", "url": "https://github.com/mycompany/privaterepo" }, { "type": "vcs", "url": "http://svn.example.org/private/repo" }, { "type": "vcs", "url": "https://github.com/mycompany/privaterepo2" } ], "require": { "company/package": "*", "company/package2": "*", "company/package3": "2.0.0" } } ``` Once you've done this, you run: ```shell php bin/satis build ``` When you ironed out that process, what you would typically do is run this command as a cron job on a server. It would then update all your package info much like Packagist does. Note that if your private packages are hosted on GitHub, your server should have an ssh key that gives it access to those packages, and then you should add the `--no-interaction` (or `-n`) flag to the command to make sure it falls back to ssh key authentication instead of prompting for a password. This is also a good trick for continuous integration servers. Set up a virtual-host that points to that `web/` directory, let's say it is `packages.example.org`. Alternatively, with PHP >= 5.4.0, you can use the built-in CLI server `php -S localhost:port -t satis-output-dir/` for a temporary solution. ### Partial Updates You can tell Satis to selectively update only particular packages or process only a repository with a given URL. This cuts down the time it takes to rebuild the `package.json` file and is helpful if you use (custom) webhooks to trigger rebuilds whenever code is pushed into one of your repositories. To rebuild only particular packages, pass the package names on the command line like so: ```shell php bin/satis build satis.json web/ this/package that/other-package ``` Note that this will still need to pull and scan all of your VCS repositories because any VCS repository might contain (on any branch) one of the selected packages. If you want to scan only the selected package and not all VCS repositories you need to declare a *name* for all your package (this only work on VCS repositories type) : ```json { "repositories": [ { "name": "company/privaterepo", "type": "vcs", "url": "https://github.com/mycompany/privaterepo" }, { "name": "private/repo", "type": "vcs", "url": "http://svn.example.org/private/repo" }, { "name": "mycompany/privaterepo2", "type": "vcs", "url": "https://github.com/mycompany/privaterepo2" } ] } ``` If you want to scan only a single repository and update all packages found in it, pass the VCS repository URL as an optional argument: ```shell php bin/satis build --repository-url https://only.my/repo.git satis.json web/ ``` ## Usage In your projects all you need to add now is your own Composer repository using the `packages.example.org` as URL, then you can require your private packages and everything should work smoothly. You don't need to copy all your repositories in every project anymore. Only that one unique repository that will update itself. ```json { "repositories": [ { "type": "composer", "url": "http://packages.example.org/" } ], "require": { "company/package": "1.2.0", "company/package2": "1.5.2", "company/package3": "dev-master" } } ``` ### Security To secure your private repository you can host it over SSH or SSL using a client certificate. In your project you can use the `options` parameter to specify the connection options for the server. Example using a custom repository using SSH (requires the SSH2 PECL extension): ```json { "repositories": [{ "type": "composer", "url": "ssh2.sftp://example.org", "options": { "ssh2": { "username": "composer", "pubkey_file": "/home/composer/.ssh/id_rsa.pub", "privkey_file": "/home/composer/.ssh/id_rsa" } } }] } ``` > **Tip:** See [ssh2 context options](https://secure.php.net/manual/en/wrappers.ssh2.php#refsect1-wrappers.ssh2-options) for more information. Example using SSL/TLS (HTTPS) using a client certificate: ```json { "repositories": [{ "type": "composer", "url": "https://example.org", "options": { "ssl": { "local_cert": "/home/composer/.ssl/composer.pem" } } }] } ``` > **Tip:** See [ssl context options](https://secure.php.net/manual/en/context.ssl.php) for more information. Example using a custom HTTP Header field for token authentication: ```json { "repositories": [{ "type": "composer", "url": "https://example.org", "options": { "http": { "header": [ "API-TOKEN: YOUR-API-TOKEN" ] } } }] } ``` ### Authentication Authentication can be handled in [several different ways](https://getcomposer.org/doc/articles/authentication-for-private-packages.md.md). ### Downloads When GitHub, GitLab or Bitbucket repositories are mirrored on your local satis, the build process will include the location of the downloads these platforms make available. This means that the repository and your setup depend on the availability of these services. At the same time, this implies that all code which is hosted somewhere else (on another service or for example in Subversion) will not have downloads available and thus installations usually take a lot longer. To enable your satis installation to create downloads for all (Git, Mercurial and Subversion) your packages, add the following to your `satis.json`: ```json { "archive": { "directory": "dist", "format": "tar", "prefix-url": "https://amazing.cdn.example.org", "skip-dev": true } } ``` #### Options explained * `directory`: required, the location of the dist files (inside the `output-dir`) * `format`: optional, `zip` (default) or `tar` * `prefix-url`: optional, location of the downloads, homepage (from `satis.json`) followed by `directory` by default * `skip-dev`: optional, `false` by default, when enabled (`true`) satis will not create downloads for branches * `absolute-directory`: optional, a _local_ directory where the dist files are dumped instead of `output-dir`/`directory` * `whitelist`: optional, if set as a list of package names, satis will only dump the dist files of these packages * `blacklist`: optional, if set as a list of package names, satis will not dump the dist files of these packages * `checksum`: optional, `true` by default, when disabled (`false`) satis will not provide the sha1 checksum for the dist files Once enabled, all downloads (include those from GitHub and Bitbucket) will be replaced with a _local_ version. #### prefix-url Prefixing the URL with another host is especially helpful if the downloads end up in a private Amazon S3 bucket or on a CDN host. A CDN would drastically improve download times and therefore package installation. Example: A `prefix-url` of `https://my-bucket.s3.amazonaws.com` (and `directory` set to `dist`) creates download URLs which look like the following: `https://my-bucket.s3.amazonaws.com/dist/vendor-package-version-ref.zip`. ### Web outputs * `output-html`: optional, `true` by default, when disabled (`false`) satis will not generate the `output-dir/index.html` page. * `twig-template`: optional, a path to a personalized [Twig](https://twig.sensiolabs.org/) template for the `output-dir/index.html` page. ### Abandoned packages To enable your satis installation to indicate that some packages are abandoned, add the following to your `satis.json`: ```json { "abandoned": { "company/package": true, "company/package2": "company/newpackage" } } ``` The `true` value indicates that the package is truly abandoned while the `"company/newpackage"` value specifies that the package is replaced by the `company/newpackage` package. Note that all packages set as abandoned in their own `composer.json` file will be marked abandoned as well. ### Resolving dependencies It is possible to make satis automatically resolve and add all dependencies for your projects. This can be used with the Downloads functionality to have a complete local mirror of packages. Add the following to your `satis.json`: ```json { "require-dependencies": true, "require-dev-dependencies": true } ``` When searching for packages, satis will attempt to resolve all the required packages from the listed repositories. Therefore, if you are requiring a package from Packagist, you will need to define it in your `satis.json`. Dev dependencies are packaged only if the `require-dev-dependencies` parameter is set to true. ### Other options * `providers`: optional, `false` by default, when enabled (`true`) each package will be dumped into a separate include file which will be only loaded by Composer when the package is really required. Speeds up composer handling for repositories with huge number of packages like f.i. packagist. * `output-dir`: optional, defines where to output the repository files if not provided as an argument when calling the `build` command. * `config`: optional, lets you define all config options from composer, except `archive-format` and `archive-dir` as the configuration is done through [archive](https://getcomposer.org/doc/articles/handling-private-packages.md.md#downloads) instead. See docs on [config schema](https://getcomposer.org/doc/06-config.md.md) for more details. * `notify-batch`: optional, specify a URL that will be called every time a user installs a package. See [notify-batch](https://getcomposer.org/doc/05-repositories.md.md#notify-batch). --- Source: https://getcomposer.org/doc/articles/plugins.md # Setting up and using plugins ## Synopsis You may wish to alter or expand Composer's functionality with your own. For example if your environment poses special requirements on the behaviour of Composer which do not apply to the majority of its users or if you wish to accomplish something with Composer in a way that is not desired by most users. In these cases you could consider creating a plugin to handle your specific logic. ## Creating a Plugin A plugin is a regular Composer package which ships its code as part of the package and may also depend on further packages. ### Plugin Package The package file is the same as any other package file but with the following requirements: 1. The [type][1] attribute must be `composer-plugin`. 2. The [extra][2] attribute must contain an element `class` defining the class name of the plugin (including namespace). If a package contains multiple plugins, this can be an array of class names. 3. You must require the special package called `composer-plugin-api` to define which Plugin API versions your plugin is compatible with. Requiring this package doesn't actually include any extra dependencies, it only specifies which version of the plugin API to use. > **Note:** When developing a plugin, although not required, it's useful to add > a require-dev dependency on `composer/composer` to have IDE autocompletion on Composer classes. The required version of the `composer-plugin-api` follows the same [rules][7] as a normal package's rules. The current Composer plugin API version is `2.11.0`. An example of a valid plugin `composer.json` file (with the autoloading part omitted and an optional require-dev dependency on `composer/composer` for IDE auto completion): ```json { "name": "my/plugin-package", "type": "composer-plugin", "require": { "composer-plugin-api": "^2.0" }, "require-dev": { "composer/composer": "^2.0" }, "extra": { "class": "My\\Plugin" } } ``` ### Plugin Class Every plugin has to supply a class which implements the [`Composer\Plugin\PluginInterface`][3]. The `activate()` method of the plugin is called after the plugin is loaded and receives an instance of [`Composer\Composer`][4] as well as an instance of [`Composer\IO\IOInterface`][5]. Using these two objects all configuration can be read and all internal objects and state can be manipulated as desired. Example: ```php getInstallationManager()->addInstaller($installer); } } ``` ## Event Handler Furthermore plugins may implement the [`Composer\EventDispatcher\EventSubscriberInterface`][6] in order to have its event handlers automatically registered with the `EventDispatcher` when the plugin is loaded. To register a method to an event, implement the method `getSubscribedEvents()` and have it return an array. The array key must be the [event name](https://getcomposer.org/doc/articles/scripts.md.md#event-names) and the value is the name of the method in this class to be called. > **Note:** If you don't know which event to listen to, you can run a Composer > command with the COMPOSER_DEBUG_EVENTS=1 environment variable set, which might > help you identify what event you are looking for. ```php public static function getSubscribedEvents() { return [ 'post-autoload-dump' => 'methodToBeCalled', // ^ event name ^ ^ method name ^ ]; } ``` By default, the priority of an event handler is set to 0. The priority can be changed by attaching a tuple where the first value is the method name, as before, and the second value is an integer representing the priority. Higher integers represent higher priorities. Priority 2 is called before priority 1, etc. ```php public static function getSubscribedEvents() { return [ // Will be called before events with priority 0 'post-autoload-dump' => ['methodToBeCalled', 1] ]; } ``` If multiple methods should be called, then an array of tuples can be attached to each event. The tuples do not need to include the priority. If it is omitted, it will default to 0. ```php public static function getSubscribedEvents() { return [ 'post-autoload-dump' => [ ['methodToBeCalled' ], // Priority defaults to 0 ['someOtherMethodName', 1], // This fires first ] ]; } ``` Here's a complete example: ```php composer = $composer; $this->io = $io; } public function deactivate(Composer $composer, IOInterface $io) { } public function uninstall(Composer $composer, IOInterface $io) { } public static function getSubscribedEvents() { return [ PluginEvents::PRE_FILE_DOWNLOAD => [ ['onPreFileDownload', 0] ], ]; } public function onPreFileDownload(PreFileDownloadEvent $event) { $protocol = parse_url($event->getProcessedUrl(), PHP_URL_SCHEME); if ($protocol === 's3') { // ... } } } ``` ## Plugin capabilities Composer defines a standard set of capabilities which may be implemented by plugins. Their goal is to make the plugin ecosystem more stable as it reduces the need to mess with [`Composer\Composer`][4]'s internal state, by providing explicit extension points for common plugin requirements. Capable Plugins classes must implement the [`Composer\Plugin\Capable`][8] interface and declare their capabilities in the `getCapabilities()` method. This method must return an array, with the _key_ as a Composer Capability class name, and the _value_ as the Plugin's own implementation class name of said Capability: ```php 'My\Composer\CommandProvider', ]; } } ``` ### Command provider The [`Composer\Plugin\Capability\CommandProvider`][9] capability allows to register additional commands for Composer: ```php setName('custom-plugin-command'); } protected function execute(InputInterface $input, OutputInterface $output): int { $output->writeln('Executing'); return 0; } } ``` Now the `custom-plugin-command` is available alongside Composer commands. > _Composer commands are based on the [Symfony Console Component][10]._ ## Running plugins manually Plugins for an event can be run manually by the `run-script` command. This works the same way as [running scripts manually](https://getcomposer.org/doc/articles/scripts.md.md#running-scripts-manually). If it is another type of plugin the best way to test it is probably using a [path repository](https://getcomposer.org/doc/05-repositories.md.md#path) to require the plugin in a test project. If you are developing locally and want to test frequently, you can make sure the path repository uses symlinks, as changes are updated immediately. Otherwise, you'll have to run `rm -rf vendor && composer update` every time you want to install/run it again. ## Using Plugins Plugin packages are automatically loaded as soon as they are installed and will be loaded when Composer starts up if they are found in the current project's list of installed packages. Additionally all plugin packages installed in the `COMPOSER_HOME` directory using the Composer global command are loaded before local project plugins are loaded. > You may pass the `--no-plugins` option to Composer commands to disable all > installed plugins. This may be particularly helpful if any of the plugins > causes errors and you wish to update or uninstall it. ## Plugin Helpers As of Composer 2, due to the fact that DownloaderInterface can sometimes return Promises and have been split up in more steps than they used to, we provide a [SyncHelper][11] to make downloading and installing packages easier. ## Plugin Extra Attributes A few special plugin capabilities can be unlocked using extra attributes in the plugin's composer.json. ### class [See above](https://getcomposer.org/doc/articles/plugins.md.md#plugin-package) for an explanation of the class attribute and how it works. ### plugin-modifies-downloads Some special plugins need to update package download URLs before they get downloaded. As of Composer 2.0, all packages are downloaded before they get installed. This means on the first installation, your plugin is not yet installed when the download occurs, and it does not get a chance to update the URLs on time. Specifying `{"extra": {"plugin-modifies-downloads": true}}` in your composer.json will hint to Composer that the plugin should be installed on its own before proceeding with the rest of the package downloads. This slightly slows down the overall installation process however, so do not use it in plugins which do not absolutely require it. ### plugin-modifies-install-path Some special plugins modify the install path of packages. As of Composer 2.2.9, you can specify `{"extra": {"plugin-modifies-install-path": true}}` in your composer.json to hint to Composer that the plugin should be activated as soon as possible to prevent any bad side-effects from Composer assuming packages are installed in another location than they actually are. ### plugin-optional Because Composer plugins can be used to perform actions which are necessary for installing a working application, like modifying which path files get stored in, skipping required plugins unintentionally can result in broken applications. So, in non-interactive mode, Composer will fail if a new plugin is not listed in ["allow-plugins"](https://getcomposer.org/doc/06-config.md.md#allow-plugins) to force users to decide if they want to execute the plugin, to avoid silent failures. As of Composer 2.5.3, you can use the setting `{"extra": {"plugin-optional": true}}` on your plugin, to tell Composer that skipping the plugin has no catastrophic consequences, and it can safely be disabled in non-interactive mode if it is not yet listed in "allow-plugins". The next interactive run of Composer will still prompt users to choose if they want to enable or disable the plugin. ## Plugin Autoloading Due to plugins being loaded by Composer at runtime, and to ensure that plugins which depend on other packages can function correctly, a runtime autoloader is created whenever a plugin is loaded. That autoloader is only configured to load with the plugin dependencies, so you may not have access to all the packages which are installed. ## Static Analysis support As of Composer 2.3.7 we ship a `phpstan/rules.neon` PHPStan config file, which provides additional error checking when working on Composer plugins. ### Usage with [PHPStan Extension Installer][13] The necessary configuration files are automatically loaded, in case your plugin projects declares a dependency to `phpstan/extension-installer`. ### Alternative manual installation To make use of it, your Composer plugin project needs a [PHPStan config file][12], which includes the `phpstan/rules.neon` file: ```neon includes: - vendor/composer/composer/phpstan/rules.neon // your remaining config.. ``` [1]: https://getcomposer.org/doc/04-schema.md.md#type [2]: https://getcomposer.org/doc/04-schema.md.md#extra [3]: https://github.com/composer/composer/blob/main/src/Composer/Plugin/PluginInterface.php [4]: https://github.com/composer/composer/blob/main/src/Composer/Composer.php [5]: https://github.com/composer/composer/blob/main/src/Composer/IO/IOInterface.php [6]: https://github.com/composer/composer/blob/main/src/Composer/EventDispatcher/EventSubscriberInterface.php [7]: https://getcomposer.org/doc/01-basic-usage.md.md#package-version-constraints [8]: https://github.com/composer/composer/blob/main/src/Composer/Plugin/Capable.php [9]: https://github.com/composer/composer/blob/main/src/Composer/Plugin/Capability/CommandProvider.php [10]: https://symfony.com/doc/current/components/console.html [11]: https://github.com/composer/composer/blob/main/src/Composer/Util/SyncHelper.php [12]: https://phpstan.org/config-reference#multiple-files [13]: https://github.com/phpstan/extension-installer#usage --- Source: https://getcomposer.org/doc/articles/repository-priorities.md # Repository priorities ## Canonical repositories When Composer resolves dependencies, it will look up a given package in the topmost repository. If that repository does not contain the package, it goes on to the next one, until one repository contains it and the process ends. Canonical repositories are better for a few reasons: - Performance wise, it is more efficient to stop looking for a package once it has been found somewhere. It also avoids loading duplicate packages in case the same package is present in several of your repositories. - Security wise, it is safer to treat them canonically as it means that packages you expect to come from your most important repositories will never be loaded from another repository instead. Let's say you have a private repository which is not canonical, and you require your private package `foo/bar ^2.0` for example. Now if someone publishes `foo/bar 2.999` to packagist.org, suddenly Composer will pick that package as it has a higher version than your latest release (say 2.4.3), and you end up installing something you may not have meant to. However, if the private repository is canonical, that 2.999 version from packagist.org will not be considered at all. There are however a few cases where you may want to specifically load some packages from a given repository, but not all. Or you may want a given repository to not be canonical, and to be only preferred if it has higher package versions than the repositories defined below. ## Default behavior By default in Composer 2.x all repositories are canonical. Composer 1.x treated all repositories as non-canonical. Another default is that the packagist.org repository is always added implicitly as the last repository, unless you [disable it](https://getcomposer.org/doc/05-repositories.md.md#disabling-packagistorg). ## Making repositories non-canonical You can add the canonical option to any repository to disable this default behavior and make sure Composer keeps looking in other repositories, even if that repository contains a given package. ```json { "repositories": [ { "type": "composer", "url": "https://example.org", "canonical": false } ] } ``` ## Filtering packages You can also filter packages which a repository will be able to load, either by selecting which ones you want, or by excluding those you do not want. For example here we want to pick only the package `foo/bar` and all the packages from `some-vendor/` from this Composer repository. ```json { "repositories": [ { "type": "composer", "url": "https://example.org", "only": ["foo/bar", "some-vendor/*"] } ] } ``` And in this other example we exclude `toy/package` from a repository, which we may not want to load in this project. ```json { "repositories": [ { "type": "composer", "url": "https://example.org", "exclude": ["toy/package"] } ] } ``` Both `only` and `exclude` should be arrays of package names, which can also contain wildcards (`*`), which will match any character. --- Source: https://getcomposer.org/doc/articles/resolving-merge-conflicts.md # Resolving merge conflicts When working as a team on the same Composer project, you will eventually run into a scenario where multiple people added, updated or removed something in the `composer.json` and `composer.lock` files in multiple branches. When those branches are eventually merged together, you will get merge conflicts. Resolving these merge conflicts is not as straight forward as on other files, especially not regarding the `composer.lock` file. > **Note:** It might not immediately be obvious why text based merging is not possible for > lock files, so let's imagine the following example where we want to merge two branches; > > - Branch 1 has added package A which requires package B. Package B is locked at version `1.0.0`. > - Branch 2 has added package C which conflicts with all versions below `1.2.0` of package B. > > A text based merge would result in package A version `1.0.0`, package B version `1.0.0` > and package C version `1.0.0`. This is an invalid result, as the conflict of package C > was not considered and would require an upgrade of package B. ## 1. Reapplying changes The safest method to merge Composer files is to accept the version from one branch and apply the changes from the other branch. An example where we have two branches: 1. Package 'A' has been added 2. Package 'B' has been removed and package 'C' is added. To resolve the conflict when we merge these two branches: - We choose the branch that has the most changes, and accept the `composer.json` and `composer.lock` files from that branch. In this case, we choose the Composer files from branch 2. - We reapply the changes from the other branch (branch 1). In this case we have to run `composer require package/A` again. ## 2. Validating your merged files Before committing, make sure the resulting `composer.json` and `composer.lock` files are valid. To do this, run the following commands: ```shell php composer.phar validate php composer.phar install [--dry-run] ``` ## Automating merge conflict resolving with git Some improvement _could_ be made to git's conflict resolving by using a custom git merge driver. An example of this can be found at [balbuf's composer git merge driver](https://github.com/balbuf/composer-git-merge-driver). ### Handling the trivial case In a small number of cases, only the `content-hash` will show as being conflicted as the version control system may be able to cleanly merge the remaining text in the file. This typically happens when two different packages have been added or updated in each side of the merge, with no overlapping nor conflicting dependencies. When this occurs, running `composer update --lock` may be enough to remove the conflict marker and update the lock file hash. You may also run any other variant of `composer update` to remove the conflict marker and potentially update packages. ## Important considerations Keep in mind that whenever merge conflicts occur on the lock file, the information, about the exact version new packages were locked on for one of the branches, is lost. When package A in branch 1 is constrained as `^1.2.0` and locked as `1.2.0`, it might get updated when branch 2 is used as baseline and a new `composer require package/A:^1.2.0` is executed, as that will use the most recent version that the constraint allows when possible. There might be a version 1.3.0 for that package available by now, which will now be used instead. Choosing the correct [version constraints](https://getcomposer.org/doc/articles/versions.md.md) and making sure the packages adhere to [semantic versioning](https://semver.org/) when using [next significant release operators](https://getcomposer.org/doc/articles/versions.md.md#next-significant-release-operators) should make sure that merging branches does not break anything by accidentally updating a dependency. # Recovering from incorrectly resolved merge conflicts If the above steps aren't followed and text based merges have been done anyway, your Composer project might be in a state where unexpected behaviour is observed because the `composer.lock` file is not (fully) in sync with the `composer.json` file. There are two things that can happen here: 1. There are packages in the `require` or `require-dev` section of the `composer.json` file that are not in the lock file and as a result never installed > **Note:** Starting from Composer release 2.5, having packages that are required but not present in `composer.lock` results in an error when running `install` 2. There are packages in the `composer.lock` file that are not a direct or indirect dependency of any of the packages required. As a result, a package is installed, even though running `composer why vendor/package` says it is not required. There are several ways to fix these issues; ## A. Start from scratch The easiest but most impactful option is run a `composer update` to resolve to a correct state from scratch. A drawback to this is that previously locked package versions are now updated, as the information about previous package versions has been lost. If all your dependencies follow [semantic versioning](https://semver.org/) and your [version constraints](https://getcomposer.org/doc/articles/versions.md.md) are using [next significant release operators](https://getcomposer.org/doc/articles/versions.md.md#next-significant-release-operators) this should not be an issue, otherwise you might inadvertently break your application. ## B. Reconstruct from the git history An option that is probably not very feasible in a lot of situations but that deserves an honorable mention; It might be possible to reconstruct the correct package state by going back into the git history and finding the most recent valid `composer.lock` file, and re-requiring the new dependencies from there. ## C. Resolve issues manually There is an option to recover from a discrepancy between the `composer.json` and `composer.lock` file without having to dig through the git history or starting from scratch. For that, we need to solve issue 1 and 2 separately. ### 1. Detecting and fixing missing required packages To detect any package that is required but not installed, you can simply run: ```shell php composer.phar validate ``` If there are packages that are required but not installed, you should get output similar to this: ```shell ./composer.json is valid but your composer.lock has some errors # Lock file errors - Required package "vendor/package-name" is not present in the lock file. This usually happens when composer files are incorrectly merged or the composer.json file is manually edited. Read more about correctly resolving merge conflicts https://getcomposer.org/doc/articles/resolving-merge-conflicts.md and prefer using the "require" command over editing the composer.json file directly https://getcomposer.org/doc/03-cli.md#require-r ``` To recover from this, simply run `composer update vendor/package-name` for each package listed here. After doing this for each package listed here, running `composer validate` again should result in no lock file errors: ```shell ./composer.json is valid ``` ### 2. Detecting and fixing superfluous packages To detect and fix packages that are locked but not a direct/indirect dependency, you can run the following command: ```shell php composer.phar remove --unused ``` If there are no packages locked that are not a dependency, the command will have the following output: ```shell No unused packages to remove ``` If there are packages to be cleaned up, the output will be as follows: ```shell vendor/package-name is not required in your composer.json and has not been removed ./composer.json has been updated Running composer update vendor/package-name Loading composer repositories with package information Updating dependencies Lock file operations: 0 installs, 0 updates, 1 removal - Removing vendor/package-name (1.0) Writing lock file Installing dependencies from lock file (including require-dev) Nothing to install, update or remove ``` --- Source: https://getcomposer.org/doc/articles/scripts.md # Scripts ## What is a script? A script, in Composer's terms, can either be a PHP callback (defined as a static method) or any command-line executable command. Scripts are useful for executing a package's custom code or package-specific commands during the Composer execution process. As of Composer 2.5 scripts can also be Symfony Console Command classes, which allows you to easily run them including passing options. This is however not recommended for handling events. > **Note:** Only scripts defined in the root package's `composer.json` are > executed. If a dependency of the root package specifies its own scripts, > Composer does not execute those additional scripts. ## Event names Composer fires the following named events during its execution process: ### Command Events - **pre-install-cmd**: occurs before the `install` command is executed with a lock file present. - **post-install-cmd**: occurs after the `install` command has been executed with a lock file present. - **pre-update-cmd**: occurs before the `update` command is executed, or before the `install` command is executed without a lock file present. - **post-update-cmd**: occurs after the `update` command has been executed, or after the `install` command has been executed without a lock file present. - **pre-status-cmd**: occurs before the `status` command is executed. - **post-status-cmd**: occurs after the `status` command has been executed. - **pre-archive-cmd**: occurs before the `archive` command is executed. - **post-archive-cmd**: occurs after the `archive` command has been executed. - **pre-autoload-dump**: occurs before the autoloader is dumped, either during `install`/`update`, or via the `dump-autoload` command. - **post-autoload-dump**: occurs after the autoloader has been dumped, either during `install`/`update`, or via the `dump-autoload` command. - **post-root-package-install**: occurs after the root package has been installed during the `create-project` command (but before its dependencies are installed). - **post-create-project-cmd**: occurs after the `create-project` command has been executed. ### Installer Events - **pre-operations-exec**: occurs before the install/upgrade/.. operations are executed when installing a lock file. Plugins that need to hook into this event will need to be installed globally to be usable, as otherwise they would not be loaded yet when a fresh install of a project happens. ### Package Events - **pre-package-install**: occurs before a package is installed. - **post-package-install**: occurs after a package has been installed. - **pre-package-update**: occurs before a package is updated. - **post-package-update**: occurs after a package has been updated. - **pre-package-uninstall**: occurs before a package is uninstalled. - **post-package-uninstall**: occurs after a package has been uninstalled. ### Plugin Events - **init**: occurs after a Composer instance is done being initialized. - **command**: occurs before any Composer Command is executed on the CLI. It provides you with access to the input and output objects of the program. - **pre-file-download**: occurs before files are downloaded and allows you to manipulate the `HttpDownloader` object prior to downloading files based on the URL to be downloaded. - **post-file-download**: occurs after package dist files are downloaded and allows you to perform additional checks on the file if required. - **pre-command-run**: occurs before a command is executed and allows you to manipulate the `InputInterface` object's options and arguments to tweak a command's behavior. - **pre-pool-create**: occurs before the Pool of packages is created, and lets you filter the list of packages that is going to enter the Solver. > **Note:** Composer makes no assumptions about the state of your dependencies > prior to `install` or `update`. Therefore, you should not specify scripts > that require Composer-managed dependencies in the `pre-update-cmd` or > `pre-install-cmd` event hooks. If you need to execute scripts prior to > `install` or `update` please make sure they are self-contained within your > root package. ## Defining scripts The root JSON object in `composer.json` should have a property called `"scripts"`, which contains pairs of named events and each event's corresponding scripts. An event's scripts can be defined as either a string (only for a single script) or an array (for single or multiple scripts.) For any given event: - Scripts execute in the order defined when their corresponding event is fired. - An array of scripts wired to a single event can contain both PHP callbacks and command-line executable commands. - PHP classes and commands containing defined callbacks must be autoloadable via Composer's autoload functionality. - Callbacks can only autoload classes from psr-0, psr-4 and classmap definitions. If a defined callback relies on functions defined outside of a class, the callback itself is responsible for loading the file containing these functions. Script definition example: ```json { "scripts": { "post-update-cmd": "MyVendor\\MyClass::postUpdate", "post-package-install": [ "MyVendor\\MyClass::postPackageInstall" ], "post-install-cmd": [ "MyVendor\\MyClass::warmCache", "phpunit -c app/" ], "post-autoload-dump": [ "MyVendor\\MyClass::postAutoloadDump" ], "post-create-project-cmd": [ "php -r \"copy('config/local-example.php', 'config/local.php');\"" ] } } ``` Using the previous definition example, here's the class `MyVendor\MyClass` that might be used to execute the PHP callbacks: ```php getComposer(); // do stuff } public static function postAutoloadDump(Event $event) { $vendorDir = $event->getComposer()->getConfig()->get('vendor-dir'); require $vendorDir . '/autoload.php'; some_function_from_an_autoloaded_file(); } public static function postPackageInstall(PackageEvent $event) { $installedPackage = $event->getOperation()->getPackage(); // do stuff } public static function warmCache(Event $event) { // make cache toasty } } ``` **Note:** During a Composer `install` or `update` command run, a variable named `COMPOSER_DEV_MODE` will be added to the environment. If the command was run with the `--no-dev` flag, this variable will be set to 0, otherwise it will be set to 1. The variable is also available while `dump-autoload` runs, and it will be set to the same as the last `install` or `update` was run in. ## Event classes When an event is fired, your PHP callback receives as first argument a `Composer\EventDispatcher\Event` object. This object has a `getName()` method that lets you retrieve the event name. Depending on the [script types](https://getcomposer.org/doc/articles/scripts.md.md#event-names) you will get various event subclasses containing various getters with relevant data and associated objects: - Base class: [`Composer\EventDispatcher\Event`](https://github.com/composer/composer/blob/main/src/Composer/EventDispatcher/Event.php) - Command Events: [`Composer\Script\Event`](https://github.com/composer/composer/blob/main/src/Composer/Script/Event.php) - Installer Events: [`Composer\Installer\InstallerEvent`](https://github.com/composer/composer/blob/main/src/Composer/Installer/InstallerEvent.php) - Package Events: [`Composer\Installer\PackageEvent`](https://github.com/composer/composer/blob/main/src/Composer/Installer/PackageEvent.php) - Plugin Events: - init: [`Composer\EventDispatcher\Event`](https://github.com/composer/composer/blob/main/src/Composer/EventDispatcher/Event.php) - command: [`Composer\Plugin\CommandEvent`](https://github.com/composer/composer/blob/main/src/Composer/Plugin/CommandEvent.php) - pre-file-download: [`Composer\Plugin\PreFileDownloadEvent`](https://github.com/composer/composer/blob/main/src/Composer/Plugin/PreFileDownloadEvent.php) - post-file-download: [`Composer\Plugin\PostFileDownloadEvent`](https://github.com/composer/composer/blob/main/src/Composer/Plugin/PostFileDownloadEvent.php) ## Running scripts manually If you would like to run the scripts for an event manually, the syntax is: ```shell php composer.phar run-script [--dev] [--no-dev] script ``` For example, `composer run-script post-install-cmd` will run any **post-install-cmd** scripts and [plugins](https://getcomposer.org/doc/articles/plugins.md.md) that have been defined. You can also give additional arguments to the script handler by appending `--` followed by the handler arguments. e.g. `composer run-script post-install-cmd -- --check` will pass`--check` along to the script handler. Those arguments are received as CLI arg by CLI handlers, and can be retrieved as an array via `$event->getArguments()` by PHP handlers. ## Writing custom commands If you add custom scripts that do not fit one of the predefined event names above, you can either run them with `run-script`, or as native Composer commands. For example, the handler defined below is executable by running `composer test`: ```json { "scripts": { "test": "phpunit", "do-something": "MyVendor\\MyClass::doSomething", "my-cmd": "MyVendor\\MyCommand" } } ``` Similar to the `run-script` command you can give additional arguments to scripts, e.g. `composer test -- --filter ` will pass `--filter ` along to the `phpunit` script. Using a PHP method via `composer do-something arg` lets you execute a `static function doSomething(\Composer\Script\Event $event)` and `arg` becomes available in `$event->getArguments()`. This however does not let you easily pass custom options in the form of `--flags`. Using a [symfony/console](https://packagist.org/packages/symfony/console) `Command` class you can describe your script, define and access arguments and options more easily. For example, with the command below you can then simply call `composer my-cmd --arbitrary-flag` without even the need for a `--` separator. To be detected as symfony/console commands, the class name must end with `Command` and extend Symfony's `Command` class. Also note that this will run using Composer's built-in symfony/console version, which may not match the one you have required in your project and may change between Composer minor releases. If you need more safety guarantees, you should rather use your own binary file that runs your own symfony/console version in isolation in its own process then. Script names and descriptions defined inside a `Command` class will override the details from your `composer.json`: the key for the entry in `scripts` (used as the command passed to `run-script`) will be replaced with either `$defaultName` or the value passed to `setName()`, and similar replacement will happen with anything included in `scripts-descriptions` for that script class. ```php setName('custom-cmd') //if this gets included, it would execute with `composer custom-cmd` instead ->setDescription('Custom description for this command') ->setDefinition([ new InputOption('arbitrary-flag', null, InputOption::VALUE_NONE, 'Example flag'), new InputArgument('foo', InputArgument::OPTIONAL, 'Optional arg'), ]) ->setHelp( "Here you can define a long description for your command\n". "This would be visible with composer my-cmd --help" ); } public function execute(InputInterface $input, OutputInterface $output): int { if ($input->getOption('arbitrary-flag')) { $output->writeln('The flag was used'); } return 0; } } ``` > **Note:** Before executing scripts, Composer's bin-dir is temporarily pushed > on top of the PATH environment variable, so that binaries of dependencies > are directly accessible. In this example, no matter if the `phpunit` binary is > actually in `vendor/bin/phpunit` or `bin/phpunit`, it will be found and executed. ## Managing the process timeout Although Composer is not intended to manage long-running processes and other such aspects of PHP projects, it can sometimes be handy to disable the process timeout on custom commands. This timeout defaults to 300 seconds and can be overridden in a variety of ways depending on the desired effect: - disable it for all commands using the config key `process-timeout`, - disable it for the current or future invocations of composer using the environment variable `COMPOSER_PROCESS_TIMEOUT`, - for a specific invocation using the `--timeout` flag of the `run-script` command, - using a static helper for specific scripts. To disable the timeout for specific scripts with the static helper directly in composer.json: ```json { "scripts": { "test": [ "Composer\\Config::disableProcessTimeout", "phpunit" ] } } ``` To disable the timeout for every script on a given project, you can use the composer.json configuration: ```json { "config": { "process-timeout": 0 } } ``` It's also possible to set the global environment variable to disable the timeout of all following scripts in the current terminal environment: ```shell export COMPOSER_PROCESS_TIMEOUT=0 ``` To disable the timeout of a single script call, you must use the `run-script` composer command and specify the `--timeout` parameter: ```shell php composer.phar run-script --timeout=0 test ``` ## Referencing scripts To enable script re-use and avoid duplicates, you can call a script from another one by prefixing the command name with `@`: ```json { "scripts": { "test": [ "@clearCache", "phpunit" ], "clearCache": "rm -rf cache/*" } } ``` You can also refer a script and pass it new arguments: ```json { "scripts": { "tests": "phpunit", "testsVerbose": "@tests -vvv" } } ``` ## Calling Composer commands To call Composer commands, you can use `@composer` which will automatically resolve to whatever composer.phar is currently being used: ```json { "scripts": { "test": [ "@composer install", "phpunit" ] } } ``` One limitation of this is that you can not call multiple composer commands in a row like `@composer install && @composer foo`. You must split them up in a JSON array of commands. ## Executing PHP scripts To execute PHP scripts, you can use `@php` which will automatically resolve to whatever php process is currently being used: ```json { "scripts": { "test": [ "@php script.php", "phpunit" ] } } ``` One limitation of this is that you can not call multiple commands in a row like `@php install && @php foo`. You must split them up in a JSON array of commands. You can also call a shell/bash script, which will have the path to the PHP executable available in it as a `PHP_BINARY` env var. ## Controlling additional arguments As of Composer 2.8, you can control how additional arguments are passed to script commands. When running scripts like `composer script-name arg arg2` or `composer script-name -- --option`, Composer will by default append `arg`, `arg2` and `--option` to the script's command. If you do not want these args in a given command, you can put `@no_additional_args` anywhere in it, that will remove the default behavior and that flag will be removed as well before running the command. If you want the args to be added somewhere else than at the very end, then you can put `@additional_args` to be able to choose exactly where they go. For example running `composer run-commands ARG` with the below config: ```json { "scripts": { "run-commands": [ "echo hello @no_additional_args", "command-with-args @additional_args && do-something-without-args --here" ] } } ``` Would end up executing these commands: ``` echo hello command-with-args ARG && do-something-without-args --here ``` ## Setting environment variables To set an environment variable in a cross-platform way, you can use `@putenv`: ```json { "scripts": { "install-phpstan": [ "@putenv COMPOSER=phpstan-composer.json", "@composer install --prefer-dist" ] } } ``` ## Custom descriptions You can set custom script descriptions with the following in your `composer.json`: ```json { "scripts-descriptions": { "test": "Run all tests!" } } ``` The descriptions are used in `composer list` or `composer run -l` commands to describe what the scripts do when the command is run. > **Note:** You can only set custom descriptions of custom commands. ## Custom aliases As of Composer 2.7, you can set custom script aliases with the following in your `composer.json`: ```json { "scripts-aliases": { "phpstan": ["stan", "analyze"] } } ``` The aliases provide alternate command names. > **Note:** You can only set custom aliases of custom commands. --- Source: https://getcomposer.org/doc/articles/troubleshooting.md # Troubleshooting This is a list of common pitfalls on using Composer, and how to avoid them. ## General 1. When facing any kind of problems using Composer, be sure to **work with the latest version**. See [self-update](https://getcomposer.org/doc/03-cli.md.md#self-update--selfupdate) for details. 2. Before asking anyone, run [`composer diagnose`](https://getcomposer.org/doc/03-cli.md.md#diagnose) to check for common problems. If it all checks out, proceed to the next steps. 3. Make sure you have no problems with your setup by running the installer's checks via `curl -sS https://getcomposer.org/installer | php -- --check`. 4. Try clearing Composer's cache by running `composer clear-cache`. 5. Ensure you're **installing vendors straight from your `composer.json`** via `rm -rf vendor && composer update -v` when troubleshooting, excluding any possible interferences with existing vendor installations or `composer.lock` entries. ## Package not found 1. Double-check you **don't have typos** in your `composer.json` or repository branches and tag names. 2. Be sure to **set the right [minimum-stability](https://getcomposer.org/doc/04-schema.md.md#minimum-stability-root-only)**. To get started or be sure this is no issue, set `minimum-stability` to "dev". 3. Packages **not coming from [Packagist](https://packagist.org/)** should always be **defined in the root package** (the package depending on all vendors). 4. Use the **same vendor and package name** throughout all branches and tags of your repository, especially when maintaining a third party fork and using `replace`. 5. If you are updating to a recently published version of a package, be aware that Packagist has a delay of up to 1 minute before new packages are visible to Composer. 6. If you are updating a single package, it may depend on newer versions itself. In this case add the `--with-dependencies` argument **or** add all dependencies which need an update to the command. ## Package is not updating to the expected version Try running `php composer.phar why-not [package-name] [expected-version]`. ## Dependencies on the root package When your root package depends on a package which ends up depending (directly or indirectly) back on the root package itself, issues can occur in two cases: 1. During development, if you are on a branch like `dev-main` and the branch has no [branch-alias](https://getcomposer.org/doc/articles/aliases.md.md#branch-alias) defined, and the dependency on the root package requires version `^2.0` for example, the `dev-main` version will not satisfy it. The best solution here is to make sure you first define a branch alias. 2. In CI (Continuous Integration) runs, the problem might be that Composer is not able to detect the version of the root package properly. If it is a git clone it is generally alright and Composer will detect the version of the current branch, but some CIs do shallow clones so that process can fail when testing pull requests and feature branches. In these cases the branch alias may then not be recognized. The best solution is to define the version you are on via an environment variable called `COMPOSER_ROOT_VERSION`. You set it to `dev-main` for example to define the root package's version as `dev-main`. Use for example: `COMPOSER_ROOT_VERSION=dev-main composer install` to export the variable only for the call to composer, or you can define it globally in the CI env vars. ## Root package version detection Composer relies on knowing the version of the root package to resolve dependencies effectively. The version of the root package is determined using a hierarchical approach: 1. **composer.json Version Field**: Firstly, Composer looks for a `version` field in the project's root `composer.json` file. If present, this field specifies the version of the root package directly. This is generally not recommended as it needs to be constantly updated, but it is an option. 2. **Environment Variable**: Composer then checks for the `COMPOSER_ROOT_VERSION` environment variable. This variable can be explicitly set by the user to define the version of the root package, providing a straightforward way to inform Composer of the exact version, especially in CI/CD environments or when the VCS method is not applicable. 3. **Version Control System (VCS) Inspection**: Composer then attempts to guess the version by interfacing with the version control system of the project. For instance, in projects versioned with Git, Composer executes specific Git commands to deduce the project's current version based on tags, branches, and commit history. If a `.git` directory is missing or the history is incomplete because CI is using a shallow clone for example, this detection may fail to find the correct version. 4. **Fallback**: If all else fails, Composer uses `1.0.0` as default version. Note that relying on the default/fallback version might potentially lead to dependency resolution issues, especially when the root package depends on a package which ends up depending (directly or indirectly) [back on the root package itself](https://getcomposer.org/doc/articles/troubleshooting.md.md#dependencies-on-the-root-package). ## Network timeout issues, curl error If you see something along the lines of: ``` Failed to download * curl error 28 while downloading * Operation timed out after 300000 milliseconds ``` It means your network is probably so slow that a request took over 300seconds to complete. This is the minimum timeout Composer will use, but you can increase it by increasing the `default_socket_timeout` value in your php.ini to something higher. ## Package not found in a Jenkins-build 1. Check the ["Package not found"](https://getcomposer.org/doc/articles/troubleshooting.md.md#package-not-found) item above. 2. The git-clone / checkout within Jenkins leaves the branch in a "detached HEAD"-state. As a result, Composer may not able to identify the version of the current checked out branch and may not be able to resolve a [dependency on the root package](https://getcomposer.org/doc/articles/troubleshooting.md.md#dependencies-on-the-root-package). To solve this problem, you can use the "Additional Behaviours" -> "Check out to specific local branch" in your Git-settings for your Jenkins-job, where your "local branch" shall be the same branch as you are checking out. Using this, the checkout will not be in detached state any more and the dependency on the root package should become satisfied. ## I have a dependency which contains a "repositories" definition in its composer.json, but it seems to be ignored. The [`repositories`](https://getcomposer.org/doc/04-schema.md.md#repositories-root-only) configuration property is defined as [root-only](https://getcomposer.org/doc/04-schema.md.md#root-package). It is not inherited. You can read more about the reasons behind this in the "[why can't Composer load repositories recursively?](https://getcomposer.org/doc/faqs/why-cant-composer-load-repositories-recursively.md.md)" article. The simplest work-around to this limitation, is moving or duplicating the `repositories` definition into your root composer.json. ## I have locked a dependency to a specific commit but get unexpected results. While Composer supports locking dependencies to a specific commit using the `#commit-ref` syntax, there are certain caveats that one should take into account. The most important one is [documented](https://getcomposer.org/doc/04-schema.md.md#package-links), but frequently overlooked: > **Note:** While this is convenient at times, it should not be how you use > packages in the long term because it comes with a technical limitation. The > composer.json metadata will still be read from the branch name you specify > before the hash. Because of that in some cases it will not be a practical > workaround, and you should always try to switch to tagged releases as soon > as you can. There is no simple work-around to this limitation. It is therefore strongly recommended that you do not use it. ## Need to override a package version Let's say your project depends on package A, which in turn depends on a specific version of package B (say 0.1). But you need a different version of said package B (say 0.11). You can fix this by aliasing version 0.11 to 0.1: composer.json: ```json { "require": { "A": "0.2", "B": "0.11 as 0.1" } } ``` See [aliases](https://getcomposer.org/doc/articles/aliases.md.md) for more information. ## Figuring out where a config value came from Use `php composer.phar config --list --source` to see where each config value originated from. ## Memory limit errors The first thing to do is to make sure you are running Composer 2, and if possible 2.2.0 or above. Composer 1 used much more memory and upgrading to the latest version will give you much better and faster results. Composer may sometimes fail on some commands with this message: `PHP Fatal error: Allowed memory size of XXXXXX bytes exhausted <...>` In this case, the PHP `memory_limit` should be increased. > **Note:** Composer internally increases the `memory_limit` to `1.5G`. To get the current `memory_limit` value, run: ```shell php -r "echo ini_get('memory_limit').PHP_EOL;" ``` Try increasing the limit in your `php.ini` file (ex. `/etc/php5/cli/php.ini` for Debian-like systems): ```ini ; Use -1 for unlimited or define an explicit value like 2G memory_limit = -1 ``` Composer also respects a memory limit defined by the `COMPOSER_MEMORY_LIMIT` environment variable: ```shell COMPOSER_MEMORY_LIMIT=-1 composer.phar <...> ``` Or, you can increase the limit with a command-line argument: ```shell php -d memory_limit=-1 composer.phar <...> ``` However, please note that setting the memory limit using these methods primarily addresses memory issues within Composer itself and its immediate processes. Child processes or external commands invoked by Composer may still require separate adjustments if they have their own memory requirements. This issue can also happen on cPanel instances, when the shell fork bomb protection is activated. For more information, see the [documentation](https://documentation.cpanel.net/display/68Docs/Shell+Fork+Bomb+Protection) of the fork bomb feature on the cPanel site. ## Xdebug impact on Composer To improve performance when the Xdebug extension is enabled, Composer automatically restarts PHP without it. You can override this behavior by using an environment variable: `COMPOSER_ALLOW_XDEBUG=1`. Composer will always show a warning if Xdebug is being used, but you can override this with an environment variable: `COMPOSER_DISABLE_XDEBUG_WARN=1`. If you see this warning unexpectedly, then the restart process has failed: please report this [issue](https://github.com/composer/composer/issues). ## "The system cannot find the path specified" (Windows) 1. Open regedit. 2. Search for an `AutoRun` key inside `HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor`, `HKEY_CURRENT_USER\Software\Microsoft\Command Processor` or `HKEY_LOCAL_MACHINE\Software\Wow6432Node\Microsoft\Command Processor`. 3. Check if it contains any path to a non-existent file, if it's the case, remove them. ## SSL certificate problem: unable to get local issuer certificate 1. Check that your root certificate store / CA bundle is up to date. Run `composer diagnose -vvv` and look for `Checked CA file ...` or `Checked directory ...` lines in the first lines of output. This will show you where Composer is looking for a CA bundle. You can get a [new cacert.pem from cURL](https://curl.se/docs/caextract.html) and store it there. 2. If this did not help despite Composer finding a valid CA bundle, try disabling your antivirus and firewall software to see if that helps. We have seen issues where Avast on Windows for example would prevent Composer from functioning correctly. To disable the HTTPS scanning in Avast you can go in "Protection > Core Shields > Web Shield > **uncheck** Enable HTTPS scanning". If this helps you should report it to the software vendor so they can hopefully improve things. ## API rate limit and OAuth tokens Because of GitHub's rate limits on their API it can happen that Composer prompts for authentication asking your username and password so it can go ahead with its work. If you would prefer not to provide your GitHub credentials to Composer you can manually create a token using the [procedure documented here](https://getcomposer.org/doc/articles/authentication-for-private-packages.md.md#github-oauth). Now Composer should install/update without asking for authentication. ## proc_open(): fork failed errors If Composer shows proc_open() fork failed on some commands: `PHP Fatal error: Uncaught exception 'ErrorException' with message 'proc_open(): fork failed - Cannot allocate memory' in phar` This could be happening because the VPS runs out of memory and has no Swap space enabled. ```shell free -m ``` ```text total used free shared buffers cached Mem: 2048 357 1690 0 0 237 -/+ buffers/cache: 119 1928 Swap: 0 0 0 ``` To enable the swap you can use for example: ```shell /bin/dd if=/dev/zero of=/var/swap.1 bs=1M count=1024 /sbin/mkswap /var/swap.1 /bin/chmod 0600 /var/swap.1 /sbin/swapon /var/swap.1 ``` You can make a permanent swap file following this [tutorial](https://www.digitalocean.com/community/tutorials/how-to-add-swap-on-ubuntu-14-04). ## proc_open(): failed to open stream errors (Windows) If Composer shows proc_open(NUL) errors on Windows: `proc_open(NUL): failed to open stream: No such file or directory` This could be happening because you are working in a _OneDrive_ directory and using a version of PHP that does not support the file system semantics of this service. The issue was fixed in PHP 7.2.23 and 7.3.10. Alternatively it could be because the Windows Null Service is not enabled. For more information, see this [issue](https://github.com/composer/composer/issues/7186#issuecomment-373134916). ## Degraded Mode Due to some intermittent issues on Travis and other systems, we introduced a degraded network mode which helps Composer finish successfully but disables a few optimizations. This is enabled automatically when an issue is first detected. If you see this issue sporadically you probably don't have to worry (a slow or overloaded network can also cause those time outs), but if it appears repeatedly you might want to look at the options below to identify and resolve it. If you have been pointed to this page, you want to check a few things: - If you are using ESET antivirus, go in "Advanced Settings" and disable "HTTP-scanner" under "web access protection" - If you are using IPv6, try disabling it. If that solves your issues, get in touch with your ISP or server host, the problem is not at the Packagist level but in the routing rules between you and Packagist (i.e. the internet at large). The best way to get these fixed is to raise awareness to the network engineers that have the power to fix it. Take a look at the next section for IPv6 workarounds. - If none of the above helped, please report the error. ## Operation timed out (IPv6 issues) You may run into errors if IPv6 is not configured correctly. A common error is: ```text The "https://getcomposer.org/version" file could not be downloaded: failed to open stream: Operation timed out ``` We recommend you fix your IPv6 setup. If that is not possible, you can try the following workarounds: **Generic Workaround:** Set the [`COMPOSER_IPRESOLVE=4`](https://getcomposer.org/doc/03-cli.md.md#composer_ipresolve) environment variable which will force curl to resolve domains using IPv4. This only works when the curl extension is used for downloads. **Workaround Linux:** On linux, it seems that running this command helps to make ipv4 traffic have a higher priority than ipv6, which is a better alternative than disabling ipv6 entirely: ```shell sudo sh -c "echo 'precedence ::ffff:0:0/96 100' >> /etc/gai.conf" ``` **Workaround Windows:** On windows the only way is to disable ipv6 entirely I am afraid (either in windows or in your home router). **Workaround Mac OS X:** Get name of your network device: ```shell networksetup -listallnetworkservices ``` Disable IPv6 on that device (in this case "Wi-Fi"): ```shell networksetup -setv6off Wi-Fi ``` Run Composer ... You can enable IPv6 again with: ```shell networksetup -setv6automatic Wi-Fi ``` That said, if this fixes your problem, please talk to your ISP about it to try to resolve the routing errors. That's the best way to get things resolved for everyone. ## Composer hangs with SSH ControlMaster When you try to install packages from a Git repository and you use the `ControlMaster` setting for your SSH connection, Composer might hang endlessly and you see a `sh` process in the `defunct` state in your process list. The reason for this is a SSH Bug: https://bugzilla.mindrot.org/show_bug.cgi?id=1988 As a workaround, open a SSH connection to your Git host before running Composer: ```shell ssh -t git@mygitserver.tld php composer.phar update ``` See also https://github.com/composer/composer/issues/4180 for more information. ## Zip archives are not unpacked correctly. Composer can unpack zipballs using either a system-provided `unzip` or `7z` (7-Zip) utility, or PHP's native `ZipArchive` class. On OSes where ZIP files can contain permissions and symlinks, we recommend installing `unzip` or `7z` as these features are not supported by `ZipArchive`. ## Disabling the pool optimizer In Composer, the `Pool` class contains all the packages that are relevant for the dependency resolving process. That is what is used to generate all the rules which are then passed on to the dependency solver. In order to improve performance, Composer tries to optimize this `Pool` by removing useless package information early on. If all goes well, you should never notice any issues with it but in case you run into an unexpected result such as an unresolvable set of dependencies or conflicts where you think Composer is wrong, you might want to disable the optimizer by using the environment variable `COMPOSER_POOL_OPTIMIZER` and run the update again like so: ```shell COMPOSER_POOL_OPTIMIZER=0 php composer.phar update ``` Now double check if the result is still the same. It will take significantly longer and use a lot more memory to run the dependency resolving process. If the result is different, you likely hit a problem in the pool optimizer. Please [report this issue](https://github.com/composer/composer/issues) so it can be fixed. --- Source: https://getcomposer.org/doc/articles/vendor-binaries.md # Vendor binaries and the `vendor/bin` directory ## What is a vendor binary? Any command line script that a Composer package would like to pass along to a user who installs the package should be listed as a vendor binary. If a package contains other scripts that are not needed by the package users (like build or compile scripts) that code should not be listed as a vendor binary. ## How is it defined? It is defined by adding the `bin` key to a project's `composer.json`. It is specified as an array of files so multiple binaries can be added for any given project. ```json { "bin": ["bin/my-script", "bin/my-other-script"] } ``` Each path is relative to the package root, and is used verbatim to generate the proxy files in `vendor/bin`. It must therefore not contain a `..` segment, nor any of the characters ``*$`"&^|<>()%!;`` or control characters. Wildcards are not expanded either, a `bin/*` entry is simply a file that does not exist. ## What does defining a vendor binary in composer.json do? It instructs Composer to install the package's binaries to `vendor/bin` for any project that **depends** on that project. This is a convenient way to expose useful scripts that would otherwise be hidden deep in the `vendor/` directory. ## What happens when Composer is run on a composer.json that defines vendor binaries? For the binaries that a package defines directly, nothing happens. ## What happens when Composer is run on a composer.json that has dependencies with vendor binaries listed? Composer looks for the binaries defined in all of the dependencies. A proxy file (or two on Windows/WSL) is created from each dependency's binaries to `vendor/bin`. Say package `my-vendor/project-a` has binaries setup like this: ```json { "name": "my-vendor/project-a", "bin": ["bin/project-a-bin"] } ``` Running `composer install` for this `composer.json` will not do anything with `bin/project-a-bin`. Say project `my-vendor/project-b` has requirements setup like this: ```json { "name": "my-vendor/project-b", "require": { "my-vendor/project-a": "*" } } ``` Running `composer install` for this `composer.json` will look at all of project-a's binaries and install them to `vendor/bin`. In this case, Composer will make `vendor/my-vendor/project-a/bin/project-a-bin` available as `vendor/bin/project-a-bin`. ## Finding the Composer autoloader from a binary As of Composer 2.2, a new `$_composer_autoload_path` global variable is defined by the bin proxy file, so that when your binary gets executed it can use it to easily locate the project's autoloader. This global will not be available however when running binaries defined by the root package itself, so you need to have a fallback in place. This can look like this for example: ```php =1.1 <2.0`, or `~4.0`). To resolve these constraints, Composer first asks the VCS to list all available tags, then creates an internal list of available versions based on these tags. In the above example, composer's internal list includes versions `1.0`, `1.0.1`, `1.0.2`, the beta release of `1.1`, the first and second release candidates of `1.1`, the final release version `1.1`, etc.... (Note that Composer automatically removes the 'v' prefix in the actual tagname to get a valid final version number.) When Composer has a complete list of available versions from your VCS, it then finds the highest version that matches all version constraints in your project (it's possible that other packages require more specific versions of the library than you do, so the version it chooses may not always be the highest available version) and it downloads a zip archive of that tag to unpack in the correct location in your `vendor` directory. ### Branches If you want Composer to check out a branch instead of a tag, you need to point it to the branch using the special `dev-*` prefix (or sometimes suffix; see below). If you're checking out a branch, it's assumed that you want to *work* on the branch and Composer actually clones the repo into the correct place in your `vendor` directory. For tags, it copies the right files without actually cloning the repo. (You can modify this behavior with --prefer-source and --prefer-dist, see [install options](https://getcomposer.org/doc/03-cli.md.md#install--i).) In the above example, if you wanted to check out the `my-feature` branch, you would specify `dev-my-feature` as the version constraint in your `require` clause. This would result in Composer cloning the `my-library` repository into my `vendor` directory and checking out the `my-feature` branch. When branch names look like versions, we have to clarify for Composer that we're trying to check out a branch and not a tag. In the above example, we have two version branches: `v1` and `v2`. To get Composer to check out one of these branches, you must specify a version constraint that looks like this: `v1.x-dev`. The `.x` is an arbitrary string that Composer requires to tell it that we're talking about the `v1` branch and not a `v1` tag (alternatively, you can name the branch `v1.x` instead of `v1`). In the case of a branch with a version-like name (`v1`, in this case), you append `-dev` as a suffix, rather than using `dev-` as a prefix. ### Stabilities Composer recognizes the following stabilities (in order of stability): dev, alpha, beta, RC, and stable where RC stands for release candidate. The stability of a version is defined by its suffix e.g version `v1.1-BETA` has a stability of `beta` and `v1.1-RC1` has a stability of `RC`. If such a suffix is missing e.g. version `v1.1` then Composer considers that version `stable`. In addition to that Composer automatically adds a `-dev` suffix to all numeric branches and prefixes all other branches imported from a VCS repository with `dev-`. In both cases the stability `dev` gets assigned. Keeping this in mind will help you in the next section. ### Minimum Stability There's one more thing that will affect which files are checked out of a library's VCS and added to your project: Composer allows you to specify stability constraints to limit which tags are considered valid. In the above example, note that the library released a beta and two release candidates for version `1.1` before the final official release. To receive these versions when running `composer install` or `composer update`, we have to explicitly tell Composer that we are ok with release candidates and beta releases (and alpha releases, if we want those). This can be done using either a project-wide `minimum-stability` value in `composer.json` or using "stability flags" in version constraints. Read more on the [schema page](https://getcomposer.org/doc/04-schema.md.md#minimum-stability-root-only). ## Writing Version Constraints Now that you have an idea of how Composer sees versions, let's talk about how to specify version constraints for your project dependencies. ### Exact Version Constraint You can specify the exact version of a package. This will tell Composer to install this version and this version only. If other dependencies require a different version, the solver will ultimately fail and abort any install or update procedures. Example: `1.0.2` ### Version Range By using comparison operators you can specify ranges of valid versions. Valid operators are `>`, `>=`, `<`, `<=`, `!=`. You can define multiple ranges. Ranges separated by a space ( ) or comma (`,`) will be treated as a **logical AND**. A double pipe (`||`) will be treated as a **logical OR**. AND has higher precedence than OR. > **Note:** Be careful when using unbounded ranges as you might end up > unexpectedly installing versions that break backwards compatibility. > Consider using the [caret](https://getcomposer.org/doc/articles/versions.md.md#caret-version-range-) operator instead for safety. > **Note:** In older versions of Composer the single pipe (`|`) was the > recommended alternative to the **logical OR**. Thus for backwards compatibility > the single pipe (`|`) will still be treated as a **logical OR**. Examples: * `>=1.0` * `>=1.0 <2.0` * `>=1.0 <1.1 || >=1.2` ### Hyphenated Version Range (` - `) Inclusive set of versions. Partial versions on the right include are completed with a wildcard. For example `1.0 - 2.0` is equivalent to `>=1.0.0 <2.1` as the `2.0` becomes `2.0.*`. On the other hand `1.0.0 - 2.1.0` is equivalent to `>=1.0.0 <=2.1.0`. Example: `1.0 - 2.0` ### Wildcard Version Range (`.*`) You can specify a pattern with a `*` wildcard. `1.0.*` is the equivalent of `>=1.0 <1.1`. Example: `1.0.*` ## Next Significant Release Operators ### Tilde Version Range (`~`) The `~` operator is best explained by example: `~1.2` is equivalent to `>=1.2 <2.0.0`, while `~1.2.3` is equivalent to `>=1.2.3 <1.3.0`. As you can see it is mostly useful for projects respecting [semantic versioning](https://semver.org/). A common usage would be to mark the minimum minor version you depend on, like `~1.2` (which allows anything up to, but not including, 2.0). Since in theory there should be no backwards compatibility breaks until 2.0, that works well. Another way of looking at it is that using `~` specifies a minimum version, but allows the last digit specified to go up. Example: `~1.2` > **Note:** Although `2.0-beta.1` is strictly before `2.0`, a version constraint > like `~1.2` would not install it. As said above `~1.2` only means the `.2` > can change but the `1.` part is fixed. > **Note:** The `~` operator has an exception on its behavior for the major > release number. This means for example that `~1` is the same as `~1.0` as > it will not allow the major number to increase trying to keep backwards > compatibility. ### Caret Version Range (`^`) The `^` operator behaves very similarly, but it sticks closer to semantic versioning, and will always allow non-breaking updates. For example `^1.2.3` is equivalent to `>=1.2.3 <2.0.0` as none of the releases until 2.0 should break backwards compatibility. For pre-1.0 versions it also acts with safety in mind and treats `^0.3` as `>=0.3.0 <0.4.0` and `^0.0.3` as `>=0.0.3 <0.0.4`. This is the recommended operator for maximum interoperability when writing library code. Example: `^1.2.3` > **Note:** If you are using PowerShell on Windows, you have to escape > carets when using them as argument on the CLI for example when using the > `composer require` command. You have to use four > subsequent caret operators, e.g. `^^^^1.2.3`, to ensure the caret operator gets > passed to Composer correctly. ## Stability Constraints If you are using a constraint that does not explicitly define a stability, Composer will default internally to `-dev` or `-stable`, depending on the operator(s) used. This happens transparently. If you wish to explicitly consider only the stable release in the comparison, add the suffix `-stable`. Examples: Constraint | Internally ------------------- | ------------------------ `1.2.3` | `=1.2.3.0-stable` `>1.2` | `>1.2.0.0-stable` `>=1.2` | `>=1.2.0.0-dev` `>=1.2-stable` | `>=1.2.0.0-stable` `<1.3` | `<1.3.0.0-dev` `<=1.3` | `<=1.3.0.0-stable` `1 - 2` | `>=1.0.0.0-dev <3.0.0.0-dev` `~1.3` | `>=1.3.0.0-dev <2.0.0.0-dev` `1.4.*` | `>=1.4.0.0-dev <1.5.0.0-dev` To allow various stabilities without enforcing them at the constraint level however, you may use [stability-flags](https://getcomposer.org/doc/04-schema.md.md#package-links) like `@` (e.g. `@dev`) to let Composer know that a given package can be installed in a different stability than your default minimum-stability setting. All available stability flags are listed on the minimum-stability section of the [schema page](https://getcomposer.org/doc/04-schema.md.md#minimum-stability-root-only). ## Summary ```jsonc "require": { "vendor/package": "1.3.2", // exactly 1.3.2 // >, <, >=, <= | specify upper / lower bounds "vendor/package": ">=1.3.2", // anything above or equal to 1.3.2 "vendor/package": "<1.3.2", // anything below 1.3.2 // * | wildcard "vendor/package": "1.3.*", // >=1.3.0 <1.4.0 // ~ | allows last digit specified to go up "vendor/package": "~1.3.2", // >=1.3.2 <1.4.0 "vendor/package": "~1.3", // >=1.3.0 <2.0.0 // ^ | doesn't allow breaking changes (major version fixed - following semver) "vendor/package": "^1.3.2", // >=1.3.2 <2.0.0 "vendor/package": "^0.3.2", // >=0.3.2 <0.4.0 // except if major version is 0 } ``` ## Testing Version Constraints You can test version constraints using [semver.madewithlove.com](https://semver.madewithlove.com). Fill in a package name and it will autofill the default version constraint which Composer would add to your `composer.json` file. You can adjust the version constraint and the tool will highlight all releases that match. --- Source: https://getcomposer.org/doc/faqs/how-do-i-install-a-package-to-a-custom-path-for-my-framework.md # How do I install a package to a custom path for my framework? Each framework may have one or many different required package installation paths. Composer can be configured to install packages to a folder other than the default `vendor` folder by using [composer/installers](https://github.com/composer/installers). If you are a **package author** and want your package installed to a custom directory, require `composer/installers` and set the appropriate `type`. Specifying the package type, will override the default installer path. This is common if your package is intended for a specific framework such as CakePHP, Drupal or WordPress. Here is an example composer.json file for a WordPress theme: ```json { "name": "you/themename", "type": "wordpress-theme", "require": { "composer/installers": "~1.0" } } ``` Now when your theme is installed with Composer it will be placed into `wp-content/themes/themename/` folder. Check the [current supported types](https://github.com/composer/installers#current-supported-package-types) for your package. As a **package consumer** you can set or override the install path for a package that requires composer/installers by configuring the `installer-paths` extra. A useful example would be for a Drupal multisite setup where the package should be installed into your site's subdirectory. Here we are overriding the install path for a module that uses composer/installers, as well as putting all packages of type `drupal-theme` into a themes folder: ```json { "extra": { "installer-paths": { "sites/example.com/modules/{$name}": ["vendor/package"], "sites/example.com/themes/{$name}": ["type:drupal-theme"] } } } ``` Now the package would be installed to your folder location, rather than the default composer/installers determined location. In addition, `installer-paths` is order-dependent, which means moving a package by name should come before the installer path of a `type:*` that matches the same package. > **Note:** You cannot use this to change the path of any package. This is only > applicable to packages that require `composer/installers` and use a custom type > that it handles. --- Source: https://getcomposer.org/doc/faqs/how-to-install-composer-programmatically.md # How do I install Composer programmatically? As noted on the download page, the installer script contains a checksum which changes when the installer code changes and as such it should not be relied upon in the long term. An alternative is to use this script which only works with UNIX utilities: ```shell #!/bin/sh EXPECTED_CHECKSUM="$(php -r 'copy("https://composer.github.io/installer.sig", "php://stdout");')" php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');" ACTUAL_CHECKSUM="$(php -r "echo hash_file('sha384', 'composer-setup.php');")" if [ "$EXPECTED_CHECKSUM" != "$ACTUAL_CHECKSUM" ] then >&2 echo 'ERROR: Invalid installer checksum' rm composer-setup.php exit 1 fi php composer-setup.php --quiet RESULT=$? rm composer-setup.php exit $RESULT ``` The script will exit with 1 in case of failure, or 0 on success, and is quiet if no error occurs. Alternatively, if you want to rely on an exact copy of the installer, you can fetch a specific version from GitHub's history. The commit hash should be enough to give it uniqueness and authenticity as long as you can trust the GitHub servers. For example: ```shell wget https://raw.githubusercontent.com/composer/getcomposer.org/f3108f64b4e1c1ce6eb462b159956461592b3e3e/web/installer -O - -q | php -- --quiet ``` You may replace the commit hash by whatever the last commit hash is on https://github.com/composer/getcomposer.org/commits/main ## Using the GitHub CLI util (`gh`) You can download and verify a `composer.phar` using the gh CLI utility as such: ```shell gh release --repo composer/composer download --pattern composer.phar gh attestation verify --repo composer/composer composer.phar ``` Use the composer.phar as is or move it where needed afterwards. --- Source: https://getcomposer.org/doc/faqs/how-to-install-untrusted-packages-safely.md # How do I install untrusted packages safely? Is it safe to run Composer as superuser or root? ## Why am I seeing a "Do not run Composer as root/super user" warning/error? It was always discouraged to run Composer as root for the reasons detailed below. As of Composer 2.4.2, plugins are disabled automatically when running as root and there is no sign that the user is consciously doing this. There are two ways this user consent can be given: - If you run interactively, Composer will prompt if you are sure that you want to continue running as root. If you run non-interactively, plugins will be disabled, unless.. - If you set the [COMPOSER_ALLOW_SUPERUSER](https://getcomposer.org/doc/03-cli.md.md#composer_allow_superuser) environment variable to `1`, this also indicates that you intended to run Composer as root and are accepting the risks of doing so. ## Is it safe to run Composer as superuser or root? Certain Composer commands, including `exec`, `install`, and `update` allow third party code to execute on your system. This is from its "plugins" and "scripts" features. Plugins and scripts have full access to the user account which runs Composer. For this reason, it is strongly advised to **avoid running Composer as super-user/root**. All commands also dispatch events which can be caught by plugins so unless explicitly disabled installed plugins will be loaded/executed by **every** Composer command. You can disable plugins and scripts during package installation or updates with the following syntax so only Composer's code, and no third party code, will execute: ```shell php composer.phar install --no-plugins --no-scripts ... php composer.phar update --no-plugins --no-scripts ... ``` Depending on the operating system we have seen cases where it is possible to trigger execution of files in the repository using specially crafted `composer.json`. So in general if you do want to install untrusted dependencies you should sandbox them completely in a container or equivalent. Also note that the `exec` command will always run third party code as the user which runs `composer`. See the [COMPOSER_ALLOW_SUPERUSER](https://getcomposer.org/doc/03-cli.md.md#composer_allow_superuser) environment variable for more info on how to disable the warnings. ## Running Composer inside Docker/Podman containers Composer makes a best effort attempt to detect that it runs inside a container and if so it will allow running as root without any further issues. If that detection fails however you will see warnings and plugins will be disabled unless you set the [COMPOSER_ALLOW_SUPERUSER](https://getcomposer.org/doc/03-cli.md.md#composer_allow_superuser) environment variable. --- Source: https://getcomposer.org/doc/faqs/how-to-use-composer-behind-a-proxy.md # How to use Composer behind a proxy Composer, like many other tools, uses environment variables to control the use of a proxy server and supports: - `http_proxy` - the proxy to use for HTTP requests - `https_proxy` - the proxy to use for HTTPS requests - `CGI_HTTP_PROXY` - the proxy to use for HTTP requests in a non-CLI context - `no_proxy` - domains that do not require a proxy These named variables are a convention, rather than an official standard, and their evolution and usage across different operating systems and tools is complex. Composer prefers the use of lowercase names, but accepts uppercase names where appropriate. ## Usage Composer requires specific environment variables for HTTP and HTTPS requests. For example: ``` http_proxy=http://proxy.com:80 https_proxy=http://proxy.com:80 ``` Uppercase names can also be used. ### Non-CLI usage Composer does not look for `http_proxy` or `HTTP_PROXY` in a non-CLI context. If you are running it this way (i.e. integration into a CMS or similar use case) you must use `CGI_HTTP_PROXY` for HTTP requests: ``` CGI_HTTP_PROXY=http://proxy.com:80 https_proxy=http://proxy.com:80 # cgi_http_proxy can also be used ``` > **Note:** CGI_HTTP_PROXY was introduced by Perl in 2001 to prevent request header manipulation and was popularized in 2016 when this vulnerability was widely reported: https://httpoxy.org ## Syntax Use `scheme://host:port` as in the examples above. Although a missing scheme defaults to http and a missing port defaults to 80/443 for http/https schemes, other tools might require these values. The host can be specified as an IP address using dotted quad notation for IPv4, or enclosed in square brackets for IPv6. ### Authorization Composer supports Basic authorization, using the `scheme://user:pass@host:port` syntax. Reserved url characters in either the user name or password must be percent-encoded. For example: ``` user: me@company pass: p@ssw$rd proxy: http://proxy.com:80 # percent-encoded authorization me%40company:p%40ssw%24rd scheme://me%40company:p%40ssw%24rd@proxy.com:80 ``` > **Note:** The user name and password components must be percent-encoded individually and then combined with the colon separator. The user name cannot contain a colon (even if percent-encoded), because the proxy will split the components on the first colon it finds. ## HTTPS proxy servers Composer supports HTTPS proxy servers, where HTTPS is the scheme used to connect to the proxy, but only from PHP 7.3 with curl version 7.52.0 and above. ``` http_proxy=https://proxy.com:443 https_proxy=https://proxy.com:443 ``` ## Bypassing the proxy for specific domains Use the `no_proxy` (or `NO_PROXY`) environment variable to set a comma-separated list of domains that the proxy should **not** be used for. ``` no_proxy=example.com # Bypasses the proxy for example.com and its sub-domains no_proxy=www.example.com # Bypasses the proxy for www.example.com and its sub-domains, but not for example.com ``` A domain can be restricted to a particular port (e.g. `:80`) and can also be specified as an IP address or an IP address block in CIDR notation. IPv6 addresses do not need to be enclosed in square brackets, like they are for http_proxy/https_proxy values, although this format is accepted. Setting the value to `*` will bypass the proxy for all requests. > **Note:** A leading dot in the domain name has no significance and is removed prior to processing. ## Deprecated environment variables Composer originally provided `HTTP_PROXY_REQUEST_FULLURI` and `HTTPS_PROXY_REQUEST_FULLURI` to help mitigate issues with misbehaving proxies. These are no longer required or used. --- Source: https://getcomposer.org/doc/faqs/should-i-commit-the-dependencies-in-my-vendor-directory.md # Should I commit the dependencies in my vendor directory? The general recommendation is **no**. The vendor directory (or wherever your dependencies are installed) should be added to `.gitignore`/`svn:ignore`/etc. The best practice is to then have all the developers use Composer to install the dependencies. Similarly, the build server, CI, deployment tools etc should be adapted to run Composer as part of their project bootstrapping. While it can be tempting to commit it in some environment, it leads to a few problems: - Large VCS repository size and diffs when you update code. - Duplication of the history of all your dependencies in your own VCS. - Adding dependencies installed via git to a git repo will show them as submodules. This is problematic because they are not real submodules, and you will run into issues. If you really feel like you must do this, you have a few options: 1. Limit yourself to installing tagged releases (no dev versions), so that you only get zipped installs, and avoid problems with the git "submodules". 2. Use --prefer-dist or set `preferred-install` to `dist` in your [config](https://getcomposer.org/doc/04-schema.md.md#config-root-only). 3. Remove the `.git` directory of every dependency after the installation, then you can add them to your git repo. You can do that with `rm -rf vendor/**/.git` in ZSH or `find vendor/ -type d -name ".git" -exec rm -rf {} \;` in Bash. But this means you will have to delete those dependencies from disk before running `composer update`. 4. Add a .gitignore rule (`/vendor/**/.git`) to ignore all the vendor `.git` folders. This approach does not require that you delete dependencies from disk prior to running a `composer update`. --- Source: https://getcomposer.org/doc/faqs/which-version-numbering-system-does-composer-itself-use.md # Which version numbering system does Composer itself use? Composer uses [Semantic Versioning (aka SemVer) 2.0.0](https://semver.org/spec/v2.0.0.html). --- Source: https://getcomposer.org/doc/faqs/why-are-unbound-version-constraints-a-bad-idea.md # Why are unbound version constraints a bad idea? A version constraint without an upper bound such as `*`, `>=3.4` or `dev-master` will allow updates to any future version of the dependency. This includes major versions breaking backward compatibility. Once a release of your package is tagged, you cannot tweak its dependencies anymore in case a dependency breaks BC - you have to do a new release, but the previous one stays broken. The only good alternative is to define an upper bound on your constraints, which you can increase in a new release after testing that your package is compatible with the new major version of your dependency. For example instead of using `>=3.4` you should use `^3.4` which allows all versions up to `3.999` but does not include `4.0` and above. The `^` operator works very well with libraries following [semantic versioning](https://semver.org). **Note:** As a package maintainer, you can help your users by providing an [alias version](https://getcomposer.org/doc/articles/aliases.md.md) for your development branch to allow it to match bound constraints. --- Source: https://getcomposer.org/doc/faqs/why-are-version-constraints-combining-comparisons-and-wildcards-a-bad-idea.md # Why are version constraints combining comparisons and wildcards a bad idea? This is a fairly common mistake people make, defining version constraints in their package requires like `>=2.*` or `>=1.1.*`. If you think about it and what it really means though, you will quickly realize that it does not make much sense. If we decompose `>=2.*`, you have two parts: - `>=2` which says the package should be in version 2.0.0 or above. - `2.*` which says the package should be between version 2.0.0 (inclusive) and 3.0.0 (exclusive). As you see, both rules agree on the fact that the package must be >=2.0.0, but it is not possible to determine if when you wrote that you were thinking of a package in version 3.0.0 or not. Should it match because you asked for `>=2` or should it not match because you asked for a `2.*`? For this reason, Composer throws an error and says that this is invalid. The way to fix it is to think about what you really mean, and use only one of those rules. --- Source: https://getcomposer.org/doc/faqs/why-cant-composer-load-repositories-recursively.md # Why can't Composer load repositories recursively? You may run into problems when using custom repositories because Composer does not load the repositories of your requirements, so you have to redefine those repositories in all your `composer.json` files. Before going into details as to why this is like that, you have to understand that the main use of custom VCS & package repositories is to temporarily try some things, or use a fork of a project until your pull request is merged, etc. You should not use them to keep track of private packages. For that you should rather look into [Private Packagist](https://packagist.com) which lets you configure all your private packages in one place, and avoids the slow-downs associated with inline VCS repositories. There are three ways the dependency solver could work with custom repositories: - Fetch the repositories of root package, get all the packages from the defined repositories, then resolve requirements. This is the current state and it works well except for the limitation of not loading repositories recursively. - Fetch the repositories of root package, while initializing packages from the defined repos, initialize recursively all repos found in those packages, and their package's packages, etc, then resolve requirements. It could work, but it slows down the initialization a lot since VCS repos can each take a few seconds, and it could end up in a completely broken state since many versions of a package could define the same packages inside a package repository, but with different dist/source. There are many ways this could go wrong. - Fetch the repositories of root package, then fetch the repositories of the first level dependencies, then fetch the repositories of their dependencies, etc, then resolve requirements. This sounds more efficient, but it suffers from the same problems as the second solution, because loading the repositories of the dependencies is not as easy as it sounds. You need to load all the repos of all the potential matches for a requirement, which again might have conflicting package definitions.