How to update composer

How to update composer

Basic usage#

Introduction#

Note: for the sake of simplicity, this introduction will assume you have performed a local install of Composer.

composer.json : Project setup#

To start using Composer in your project, all you need is a composer.json file. This file describes the dependencies of your project and may 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 key. You are telling Composer which packages your project depends on.

As you can see, 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 key, or in 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, and about repositories).

Package names#

Read more about publishing packages and package naming. (Note that you can also specify «platform packages» as dependencies, allowing you to require certain versions of server software. See platform packages below.)

Package version constraints#

Please read versions for more in-depth information on versions, how versions relate to each other, and on version constraints.

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.

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.

Installing dependencies#

To initially install the defined dependencies for your project, you should run the update command.

This will make Composer do two things:

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 the dependencies installed are still working even if your dependencies released many new versions since then. (See note below about using the update command.)

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).

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.

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 command. This will fetch the latest matching versions (according to your composer.json file) and update the lock file with the new versions.

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:

Packagist#

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, 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.

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:

Composer will register a 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 field, you have to re-run this command:

This command will re-generate the vendor/autoload.php file. See the dump-autoload 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.

In addition to PSR-4 autoloading, Composer also supports PSR-0, classmap and files autoloading. See the autoload reference for more information.

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.

Found a typo? Something is wrong in this documentation? Fork and edit it!

Composer and all content on this site are released under the MIT license.

How to update Composer in Windows 10

I am using Composer for my PHP project. I am new to Composer. Now when I update my dependencies using composer update command, it is saying that my Composer version is too old and ask me to update. So I tried as below. But all failed.

My composer.phar file is in C:/ProgramData/ComposerSetup/bin/composer.phar

I opened terminal and tried

How to update composer. Смотреть фото How to update composer. Смотреть картинку How to update composer. Картинка про How to update composer. Фото How to update composer

All command failed. I am using XAMPP. There is no composer.phar file in xampp/php folder as well. How can I update Composer in Windows 10?

How to update composer. Смотреть фото How to update composer. Смотреть картинку How to update composer. Картинка про How to update composer. Фото How to update composer

How to update composer. Смотреть фото How to update composer. Смотреть картинку How to update composer. Картинка про How to update composer. Фото How to update composer

5 Answers 5

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

If this doesn’t work check your PATH variable, if it’s not there try searching composer.bat in windows and add it to your PATH variable. Normally, its in following path.

How to update composer. Смотреть фото How to update composer. Смотреть картинку How to update composer. Картинка про How to update composer. Фото How to update composer

Windows 10 update for Composer still works (end of 2020, pre version 2) with:

Follow This below Image: How to update composer. Смотреть фото How to update composer. Смотреть картинку How to update composer. Картинка про How to update composer. Фото How to update composer

composer self-update:

How easy is it to upgrade?

Composer для самых маленьких

Когда я первый раз разбирался с composer, я набросал для себя маленькую шпаргалку и теперь, спустя некоторое время представляю её на суд общественности в несколько доработанном виде.
Данная публикация актуальная для тех, кто в первый раз столкнулся с незаменимым менеджером пакетов для PHP.

Итак, Composer — менеджер пакетов для PHP.

Для чего нужен Composer и простейший пример его использования

Возьмем для примера этот проект
Если в двух словах: то это набор скриптов для работы в VK API
Соответственно, для работы этих скриптов нужно несколько библиотек
Библиотеки перечислены в файле composer.json — ключевой файл при работе с composer

В этом проекте используется 5 библиотек. Соответственно, если разработчик решит опубликовать этот проект на github, то ему достаточно закинуть в репу саму папку со скриптами и составить composer.json, в котором будут описаны библиотеки, необходимые для работы этого проекта. Простота очевидна: в репу не нужно вслед за файлами прицепом тащить все нужные библиотеки. Занимает меньше места, проще распространять проект.

В папке scripts лежат непосредственно скрипты проекта, для работы которых и требуются эти 5 пакетов.

Запускаем установку пакетов:

После установки появляется папка vendor, куда складываются установленные пакеты и формируется файл autoload.php

Этот файл подключаем к проекту и всё — библиотеки подключены, можно спокойно с ними работать.

Простота очевидна: не нужно скачивать и подключать библиотеки и их зависимости самостоятельно, composer всё сделает за Вас. И вся эта пачка подключается одним единственным файлом autoload.php
Все пакеты, которые лежат в vendor, добавляются в автозагрузчик. При этом composer опирается на файлы composer.json, которые должны быть у каждого пакета. Формирование composer.json пакета — это задача разработчика пакета, от потребителя пакета требуется лишь описать в composer.json проекта, какие пакеты нужно подключить.

Это пример composer.json проекта:

Это пример composer.json пакета:

В секции require прописана зависимость этого пакета — библиотека guzzle http, необходимая для работы библиотеки getjump/vk. В данном случае, т.е. с точки зрения потребителя пакетов, всевозможные зависимости пакетов — это не наша «забота», с зависимостями composer разберётся сам.

Пространство имён пакета прописано в секции autoload

getjump\\Vk\\ — наименование пространства имён
src/getjump/Vk/ — директория, в которой лежат файлы с классами пакета
Работа с этой библиотекой в проекте:

Core и Friends — это классы библиотеки, которые разложены и прописаны в папке src в соответствии со стандартом PSR-4. Опять же формирование структуры пакета — это работа создателя пакета.
Нам, как потребителю пакета, достаточно прописать в наш проект
include ‘../vendor/autoload.php’;
и все эти классы и пространства имён будут отлично работать.
При этом нам не нужно заморачиваться и писать автозагрузчик. Composer это сделает сам при выполнении команды install.

Установка

Установка Composer глобально

1) Для начала нужно что бы путь к директории с интерпретатором PHP был прописан в переменной окружения path.
Проверим, так ли это:
php –version

Далее нас будет интересовать переменная path:

Вписываем путь к интерпретатору

*С давних времён у меня на компьютере лежит сборка xampp, сама сборка здесь нафиг не нужна, а вот интерпретатор с неё вполне подойдёт (версия PHP – 5.6).

3) Добавим в переменную окружения path путь к composer.bat, например для D:\bin должно получиться:

Дополнительно можно добавить в path
D:\Users\%userName%\AppData\Roaming\Composer\vendor\bin\
для того, что-бы было удобнее использовать инструменты, глобально установленные через Composer.
(У меня папка Users располагается на диске D, а на C создан симлинк на неё).
Всё, composer установлен и полностью готов к работе.

Ещё: при установке можно словить ошибку
[RuntimeException]
The APPDATA or COMPOSER_HOME environment variable must be set for composer to run correctly
Решение нашлось здесь github.com/composer/composer/issues/2033
Добавляем переменную APPDATA со значением D:\Users\GSU\AppData\Roaming

Установка Composer локально

Отличия глобальной и локальной установки

Команды запускаются по разному при локальной и глобальной установках:

Например:
Локально: php composer.phar require silex/silex

1.1
Глобально: composer require silex/silex

При глобальной установке этот файл не нужен. Composer запускается при любой текущей директории.

Команды

Синтаксис composer.json

Именование пакетов и варианты описания пакетов

Имя пакета состоит из двух частей разделёных косой чертой: названия поставщика (vendor name) и названия библиотеки.

Если пакет оформлен в соответствии со стандартом PSR-4, но опубликован не на packagist.org, а на github, то вместо версии пакета нужно прописать ветку и репозиторий для этого пакета:

Пример подключения библиотеки, которая лежит на github, но при этом не оформлена по стандарту PSR-4, а представляет из себя обыкновенное нагромождение файлов с классами и функциями.

Pqr/superlib — эта та самая «неправильная» библиотека.

В секции repositories для неё пишем такую конструкцию

Ключевой момент — секция autoload, здесь указываем нужные нам файлы с классами и функциями.
Структура библиотеки:

Как пользоваться Composer

Язык программирования PHP очень стремительно развивается. Ещё несколько лет назад огромным количеством библиотек на все случаи жизни мог похвастаться только Python. Однако сейчас уже разработано огромное количество библиотек для PHP, и все они доступны для установки буквально в несколько команд.

Для этого можно использовать пакетный менеджер composer. Утилита позволяет не только устанавливать сторонние пакеты, но и обновлять их при выходе новых версий, разрешать зависимости, а также очень легко создавать пакеты для своих библиотек. В этой статье мы рассмотрим, как пользоваться Composer для управления пакетами в PHP.

Синтаксис и опции Composer

$ composer опции команда

Опций у самой утилиты не так уж много. Давайте рассмотрим самые полезные:

Более интересны команды, которые вы будете постоянно использовать:

Большинство из этих опций мы разберём чуть ниже, в примерах использования composer. А пока давайте посмотрим, как его установить.

Установка Composer

Прежде, чем что-либо делать, утилиту надо установить. Инсталлировать Composer можно глобально для всей операционной системы или только в опредёленную папку. Для глобальной установки в Ubuntu используйте команду:

sudo apt install composer

Кроме того, существует возможность установки утилиты в ту папку, в которой будет ваш проект. Для этого сначала создайте папку и перейдите в неё:

mkdir new_project && cd new_project

Затем скачайте последнюю версию утилиты такой командой:

Установка Composer выполняется командой:

How to update composer. Смотреть фото How to update composer. Смотреть картинку How to update composer. Картинка про How to update composer. Фото How to update composer

После установки в директории появится файл Сomposer.phar, который и следует запускать для работы с утилитой. В Windows вы можете установить Composer только таким способом. Дальше в статье я буду считать, что утилита установлена глобально в системе, но дела это не меняет, просто будет отличаться имя исполняемого файла:

Важно отметить, что для работы последней версии утилиты необходимо, чтобы в вашей системе была установлена версия PHP не ниже 7.0. Иначе утилита установится, но во время запуска будут выдаваться ошибки. Если вы используете панель управления, в которой есть несколько версий PHP, то нужно передать путь к утилите бинарному файлу PHP нужной версии, например:

Путь к бинарному файлу будет отличаться в зависимости от способа установки PHP, панели и версии интерпретатора.

Версия утилиты, установленная из официального сайта, будет, как правило? намного свежее, чем из репозиториев:

How to update composer. Смотреть фото How to update composer. Смотреть картинку How to update composer. Картинка про How to update composer. Фото How to update composer

Чтобы удалить Composer, достаточно удалить его файлы из папки, куда он был установлен. Чтобы обновить Composer до последней версии, выполните:

php composer.phar self-update

Теперь пора переходить к примерам работы с Composer.

Как пользоваться Composer

1. Проект на основе пакета

Чаще всего вы будете разворачивать проекты Composer на основе уже существующих пакетов. В этом случае утилита берёт пакет из репозитория и просто распаковывает его в текущую папку, а все зависимости уже помещаются в папку vendor. Для этого используется команда create-project. Давайте создадим проект на основе пакета slim/slim4-skeleton:

How to update composer. Смотреть фото How to update composer. Смотреть картинку How to update composer. Картинка про How to update composer. Фото How to update composer

Вторым параметром утилите надо передать папку, в которой будет развёрнут проект. В данном случае это текущая папка. После завершения установки вы получите уже развёрнутое приложение и можете начинать его модифицировать.

2. Установка пакетов

Для установки пакетов в Composer используется команда require. Утилита установит нужный пакет в подпапку vendor, добавит его в автозагрузку и в файл composer.json. Например, установим пакет illuminate/eloquent:

composer require illuminate/eloquent

Кроме того, composer позволяет устанавливать пакеты, которые будут доступны только для разработчика. Для этого используйте опцию —dev:

Бывают случаи, когда пакет не хочет устанавливаться из-за несовместимости с платформой. В первую очередь надо убедится, что все необходимые ему расширения PHP в системе установлены. Если же ваша консольная версия PHP использует другие расширения, а сам пакет будет использоваться только с веб-сервером, можно отключить проверку системных требований пакета с помощью опции —ignore-platform-reqs:

Все пакеты Composer могут иметь два уровня стабильности:

Уровень стабильности пакета определяет его разработчик. Эта проблема решается чуть сложнее, надо поменять минимальный уровень стабильности для вашего проекта на dev. Откройте файл composer.json и под строчкой License добавьте следующую строчку:

How to update composer. Смотреть фото How to update composer. Смотреть картинку How to update composer. Картинка про How to update composer. Фото How to update composer

Или, если в файле уже есть строчка minimum-stability, необходимо заменить её значения со stable на dev. После этого вы сможете установить пакет composer, который вам необходим. Напоминаю, что все команды Сomposer аналогичны, даже если Сomposer на хостинге, а не на локальной машине или VPS-сервере, надо только указать верный путь к его исполняемому файлу.

3. Удаление пакетов

Чтобы удалить пакет, который вам больше не нужен, используйте опцию remove:

composer remove illuminate/eloquent

Аналогичным образом удаляется пакет для разработчиков:

4. Обновление пакетов

Чтобы в ваших пакетах не было уязвимостей и старых проблем, необходимо регулярно их обновлять. Для этого используется команда update. Обратите внимание, что обновляются пакеты только в текущей директории, а не по всей системе, поэтому обновлять придётся каждый проект по отдельности:

И для пакетов разработчиков:

5. Сброс автозагрузки

Бывает, что вы создали новый класс или установили пакет, но классы из него всё ещё не видны, и при попытке обратится к ним вы получаете ошибку. В таком случае следует обновить кэш автозагрузки Composer:

How to update composer. Смотреть фото How to update composer. Смотреть картинку How to update composer. Картинка про How to update composer. Фото How to update composer

6. Создание пакета

Теперь вы знаете, как использовать Composer, давайте немного поговорим о создании своих пакетов. Чтобы создать пустой проект в текущей папке, достаточно выполнить команду:

Утилита задаст несколько вопросов:

How to update composer. Смотреть фото How to update composer. Смотреть картинку How to update composer. Картинка про How to update composer. Фото How to update composer

На последнем шаге утилита предложит вам проверить, всё ли верно указано в конфигурационном файле:

How to update composer. Смотреть фото How to update composer. Смотреть картинку How to update composer. Картинка про How to update composer. Фото How to update composer

После чего будет создан файл composer.json, и вы сможете установить нужные пакеты и добавлять свои исходные файлы. Я не буду писать здесь про автозагрузку PSR-4 и другие возможности composer.json, так, как это уже выходит за рамки обычного использования утилиты и больше касается разработки.

После того, как проект был создан, вы можете создать в папке проекта git-репозиторий и загрузить его на GitHub или другой сервис. Сразу же после этого ваш пакет можно будет установить с помощью Composer в любой другой проект, просто добавив его репозиторий.

7. Установка пакетов из сторонних репозиториев

Сначала нужно добавить ссылку на репозиторий в composer.json. Я предполагаю, что ваш репозиторий публичный, значит никаких ключей авторизации не понадобится:

«repositories»: [
<
«type»: «vcs»,
«url»: «ссылка на git репозиторий»
>
]

How to update composer. Смотреть фото How to update composer. Смотреть картинку How to update composer. Картинка про How to update composer. Фото How to update composer

Секцию repositories надо добавлять на тот же уровень, что и license. и другие основные секции. Затем можно просто установить свой пакет:

composer require sergiy/selenium-chrome-library

How to update composer. Смотреть фото How to update composer. Смотреть картинку How to update composer. Картинка про How to update composer. Фото How to update composer

После этого папка пакета появится в подпапке vendor, а его классы будут добавлены в автозагрузку.

Выводы

В этой статье мы разобрались, как пользоваться Composer для установки различных пакетов PHP, как обновлять эти пакеты, а также как создать свой пакет с программой и применять его в других своих проектах. Не может не радовать, что у PHP появился и увеличивается каталог библиотек, которые позволяют реализовать если не всё, то очень многое.

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.

As Composer uses symfony/console you can call commands by short name if it’s not ambiguous.

Bash Completions#

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:

Process Exit Codes#

In the Libraries 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.

Options

install / i#

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

update / u#

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.

If you only want to update a few packages and not all, you can list them as such:

You can also use wildcards to update a bunch of packages at once:

The custom constraint has to be a subset of the existing constraint you have, and this feature is only available for your root package dependencies.

Options

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.

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.

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.

Options

remove#

The remove command removes packages from the composer.json file from the current directory.

After removing the requirements, the modified requirements will be uninstalled.

Options

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.

Options

reinstall#

You can specify more than one package name to reinstall, or use a wildcard to select several packages at once:

Options

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.

global#

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:

If you wish to update the binary later on you can run a 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.

You can also search for more than one term by passing multiple arguments.

Options

To list all of the available packages, you can use the show command.

To filter the list you can pass a package mask using wildcards.

If you want to see the details of a certain package, you can pass the package name.

You can even pass the package version, which will tell you the details of that specific version.

Options

outdated#

The color coding is as such:

Options

browse / home#

The browse (aliased to home ) opens a package’s repository URL or homepage in your browser.

Options

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.

Options

Options

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.

You can optionally specify a version constraint after the package to limit the search.

Options

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:

Note that you can also specify platform requirements, for example to check whether you can upgrade your server to PHP 8.0:

As with depends you can request a recursive lookup, which will list all packages depending on the packages that cause the conflict.

Options

validate#

You should always run the validate command before you commit your composer.json file, and before you tag a release. It will check if your composer.json is valid.

Options

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.

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.

If you would like to instead update to a specific release specify it:

If you have installed Composer for your entire system (see global installation), you may have to run the command with root privileges

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.)

Options

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.

Usage#

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:

See the Config chapter for valid configuration options.

Options

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:

If your repository requires more configuration options, you can instead pass its JSON representation :

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:

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:

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.

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

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

clear-cache / clearcache / cc#

Deletes all content from Composer’s cache directories.

Options

licenses#

Options

run-script#

Options

To run scripts manually you can use this command, give it the script name and optionally any required arguments.

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

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.

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.

Options

audit#

This command is used to audit the packages you have installed for possible security issues. It checks for and lists security vulnerability advisories according to the Packagist.org api.

Options

Command-line completion#

Command-line completion can be enabled by following instructions on this page.

Environment variables#

COMPOSER#

By setting the COMPOSER env variable it is possible to set the filename of composer.json to something else.

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_XDEBUG#

If set to 1, this env allows running Composer when the Xdebug extension is enabled, without restarting PHP without it.

COMPOSER_AUTH#

COMPOSER_BIN_DIR#

COMPOSER_CACHE_DIR#

The COMPOSER_CACHE_DIR var allows you to change the Composer cache directory, which is also configurable via the cache-dir option.

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 config option.

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.

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 and configuration 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#

COMPOSER_MEMORY_LIMIT#

If set, the value is used as php’s memory_limit.

COMPOSER_MIRROR_PATH_REPOS#

COMPOSER_NO_INTERACTION#

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#

COMPOSER_VENDOR_DIR#

COMPOSER_RUNTIME_ENV#

http_proxy or HTTP_PROXY#

If you are using Composer from behind an HTTP proxy, you can use the standard http_proxy or HTTP_PROXY env vars. Set it to the URL of your proxy. Many operating systems already set this variable for you.

If you are using Composer in a non-CLI context (i.e. integration into a CMS or similar use case), and need to support proxies, please provide the CGI_HTTP_PROXY environment variable instead. See httpoxy.org for further details.

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.

HTTP_PROXY_REQUEST_FULLURI#

If you use a proxy, but it does not support the request_fulluri flag, then you should set this env var to false or 0 to prevent Composer from setting the request_fulluri option.

HTTPS_PROXY_REQUEST_FULLURI#

If you use a proxy, but it does not support the request_fulluri flag for HTTPS requests, then you should set this env var to false or 0 to prevent Composer from setting the request_fulluri option.

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.

no_proxy or NO_PROXY#

If you are behind a proxy and would like to disable it for certain domains, you can use the no_proxy or NO_PROXY env var. Set it to a comma separated list of domains the proxy should not be used for.

The env var accepts domains, IP addresses, and IP address blocks in CIDR notation. You can restrict the filter to a particular port (e.g. :80 ). You can also set it to * to ignore the proxy for all HTTP requests.

COMPOSER_DISABLE_NETWORK#

COMPOSER_DEBUG_EVENTS#

COMPOSER_NO_DEV#

COMPOSER_PREFER_STABLE#

COMPOSER_PREFER_LOWEST#

COMPOSER_IGNORE_PLATFORM_REQ or COMPOSER_IGNORE_PLATFORM_REQS#

Found a typo? Something is wrong in this documentation? Fork and edit it!

Composer and all content on this site are released under the MIT license.

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *