composer dump autoload что делает

Автозагрузка классов с помощью Composer.

Для внесения своих данных в файлы автозагрузчика Composer, нужно внести изменения в файл composer.json, а если его еще нет в корне приложения – создать.
Создание осуществляется с помощью выполнения в командной строке, например в консоли OpenServera:

Перед этим нужно перейти в корневой каталог приложения.
Если Composer установлен не глобально, то вместо composer нужно писать php composer.phar.

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

Если же создавать данный файл с помощью команды composer init или использовать файл который уже имеется (если объект autoload отсутствует), то нужно поставить запятую после последнего элемента (но до последней фигурной скобки) и вписать блок autoload.

В данном примере указано, что для автозагрузчика будет использоваться стандарт кодирования PSR-4, согласно которому используется пространство имен классов, файлы классов имеют названия соответствующие названиям находящихся в них классов и тд. подробнее https://zenwalker.me/blog/php-psr-0-vs-psr-4

Согласно примера, для пространства имен начинающегося с Services должна подключаться папка с названием services, находящаяся в корне приложения. С App аналогично.
То есть, например, класс Services\Application должен находиться в папке services/Application.php, тогда Composer автоматически подключит его.

Раздел autoload может включать и другие подразделы: classmap, files.

Подраздел classmap отвечает за описание классов, именование которых не соответствует стандарту PSR-4. То есть, в карте классов мы просто указываем где искать определенные классы. Например:

Тут первым элементом массива classmap указываем каталог в котором нужно искать требуемые файлы классов. При этом не уточняем название класса.
Вторым элементом показан пример указания конкретного файла класса, чтобы Composer не приходилось искать в папке services/myserv что-то еще. Конечно стоит прописывать или первый или второй вариант.

То есть структура блока autoload может включать разные компоненты:

После вписывания нужного кода в объект autoload, сохраняем изменения и далее нужно выполнить обновление файлов автозагрузчика Composer. Если файл composer.json вы сами перед этим создавали, то файлов автозагрузчика еще и вовсе нет. Для того, чтобы они появились, выполните
создастся папка vendor, а в ней папка composer с файлами автозагрузки. Там же будет файл autoload_psr4.php в котором перезаписаны наши правила поиска классов согласно стандарта psr-4 и аналогичные файлы для карты классов и файлов.

Если папка vendor с данными файлами уже была, а вам нужно изменить данные для подключения своих классов, то нужно выполнить команду:
которая обновит файлы автозагрузчика Composer и при этом не будут устанавливаться и обновляться зависимости (библиотеки прописанные в блоке require).
Используя после команды ключ «-o», что значит «optimize», классы соответствующие стандарту psr-4 и прописанные для данного объекта будут прописаны в карте классов, что ускорит их загрузку в дальнейшем.

Источник

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.

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#

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

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.

Читайте также:  launch json visual studio code что это

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 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 ), more than one 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 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.

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

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

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.

Источник

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

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

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

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

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

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

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

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

Установка Composer

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

Читайте также:  при росте 192 какой должен быть вес у мужчин

sudo apt install composer

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

mkdir new_project && cd new_project

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

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

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

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

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

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

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

php composer.phar self-update

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

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

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

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

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

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

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

composer require illuminate/eloquent

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

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

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

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

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

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

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

composer remove illuminate/eloquent

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

composer require sergiy/selenium-chrome-library

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

Выводы

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

Источник

Сказочный портал