composer set php version

Force composer to require PHP Version between Version X and Version Y

we have a mix of different PHP versions running on your servers (max 5.3.5) and development machines (max 5.5.9).

Now we ran into the problem that we did a «composer update» to get the latest Version of some external Bundles. Since your composer.json looks like

we get some Bundles that required PHP 5.5. No problem on our dev machines, but on the server 🙁

Is there any possibility to tell composer to require a PHP version between 5.3.3 and 5.3.5? Or a max available Version?

but both didn’t work out. I get a «The requested package php could not be found in any version, there may be a typo in the package name.» Error.

Any Ideas? Thanks in advance

6 Answers 6

Since the config parameter in composer.json is available. You could something like this:

I find it questionable to say the least that you are developing with the newest PHP available and are running production with a very outdated version. There will be plenty of possible problems arising from this, not only because of security patches that you would be missing, but more importantly because of PHP bug fixes that got introduced mostly in versions 5.3.9 and 5.3.23 that changes PHP behavior in some details pretty fundamentally. Not talking about the risk of accidentally using features of 5.4 or 5.5.

And there really is no way to make Composer deal with this situation. The PHP version that is used when running composer update determines the resolution of dependencies, being influenced by PHP version and installed PHP extensions.

You cannot define that a package should only be used for PHP versions between 5.3.3 and 5.3.5 if the PHP you are using for the update is not matching this version requirement. Because the used PHP version exceeds the upper version constraint, such a package is not eligible for fulfilling the version requirement, and Composer reports that no package has been found (not telling that it has seen the packages, but they had to be ignored because of the version constraint).

There are probably three obvious ways out:

Downgrade your development environment to the production version you are really using. If more than one is used: The oldest one. That way any requirements for PHP versions will be matched. Run composer update then, and you are done.

Upgrade your production environment. Needs no further explanation, but I have to mention that not only are you missing a lot of very nice PHP features, you are also missing a substantial performance increase, because PHP 5.5 is really that much faster than 5.3.

Источник

How to change PHP version used by composer

How can I use PHP7 without reinstalling the composer again?

9 Answers 9

You can change php version of composer without uninstalling it, follow these steps :

I’m assuming Windows if you’re using WAMP. Composer likely is just using the PHP set in your path: How to access PHP with the Command Line on Windows?

You should be able to change the path to PHP using the same instructions.

Otherwise, composer is just a PHAR file, you can download the PHAR and execute it using any PHP:

composer set php version

Use which composer command to help locate the composer executable.

composer set php version

Another possibility to make composer think you’re using the correct version of PHP is to add to the config section of a composer.json file a platform option, like this:

Where is the PHP version of your choice.

Snippet from the docs:

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

Old question I know, but just to add some additional information:

Note: It is important to understand that the «PHP CLI Version» is used by WAMP’s own internal PHP scripts. This «PHP CLI Version» has nothing to do with the version you wish to use for your scripts, Composer or anything else.

For your scripts to work with the version you require, you need to add it’s path to the Users Environmental Path. You could add it to the Systems environmental Path but the Users Path is the recommended option.

From WAMP v3.1.2, it would display an error when it detect reference to a PHP path in the System or User Environmental Path. This was to stop confusion such as you were experiencing. Since v3.1.7 the display of this error can now be optionally displayed through a selection in the WampSettings menu.

As indicated in previous answers, adding an installed PHP path (such as «C:\wamp64\bin\php\php7.2.30») to the Users Environmental Path is the correct approach. PS: As the value of the Users Environmental Path is a string, all paths added must be separated with a semi-colon (;)

After experiencing the exact same problem (IE: Choosing which version of PHP I wanted Composer to use), I created a script which could easily and rapidly switch between PHP CLI Versions depending on what project I was working on.

Источник

Tell Composer to use Different PHP Version

I’ve been stuck at this for a few days. I’m using 1and1 hosting, and they have their PHP set up a bit weird.

Is there any way to tell Composer to use the php5.5 command? Has anyone successfully gotten Composer configured on 1and1 hosting?

I’m trying to get Laravel up and running (which uses Composer). I’ve been able to do it on my GoDaddy domain, but not 1and1.

21 Answers 21

composer set php version

Just add below code to your composer.json file to set different php version:

composer set php version

On xubuntu I had php 7.2 as default. But needed to run composer with php 5.6.

So this worked for me:

If you just need to get composer to ignore the version requirements, you can bypass using:

composer is a PHP binary script and it’s using Unix Shebang to define which interpreter for executing.

So if you’re running composer without any specific option, it will use your PHP version at /usr/bin/env php (which is your default PHP)

We can have many versions of PHP inside your Linux and you can flexible use which PHP version for executing as you want like this way:

To check & find all installed PHP packages, goto /usr/bin/

composer set php version

You always can use that way.

In project folder where you has composer.json file. Run the command

where php7.4 your specific version can be(php7.0, php5.5, php7.3 etc. ) where /usr/local/bin/composer path for system folder with composer

. you should have php7.4-cli

That way for linux/ubuntu user

composer set php version

composer set php version

I too have a shared hosting account on 1&1 (ionos) and here’s what I have had to do:

if you login as the root ssh account, you can create a

/.bash_profile and add

to it so that you can now use the commands you would normally use and it just works. (put composer.phar in your project folder root)

Then, make sure your laravel composer.lock file from your dev machine gets up to your project folder on 1and1 and run

Using this tip from @tobymackenzie: on shared hosts you really should just run composer install (not update!) from a composer.lock file you created on your own machine. That way the memory usage remains very low.

Hope this helps somebody.

Step 01:- Add below code to your composer.json file

Step 02:- Then, run the below command.

You could change your PATH to override the php version.

In /home/user/bin (or any other directory really) make a symlink named php to the php5 binary.

Another option, use a shell alias:

composer set php version

composer set php version

There are two ways to do it.

composer set php version

composer set php version

The existing answers partly do not answer the question, give suggestions that do not work or give bad advice.

The question stated:

However, I can run php5.5 composer.phar install, get a little bit further, but it still fails because somewhere along the line, PHP is called again, but it fails, as it’s using 4.4.6.

Instead, I am here showing a way to test and verify the suggestions.

I wish I had a better answer myself but I am unsure what is the best solution. Personally I would go with a solution which make sure PHP is called with the correct version on the host (e.g. via an alias or setting the PHP environment correctly, running the entire operation inside a container or some other solution), regardless of Composer and add a platform php constraint.

If you don’t run any scripts and just need the requirements to resolve the dependencies correctly config:platform:php would probably be your friend.

Let’s say our default php version is 7.4 but our project requires 7.2.

Check your default PHP version

Create a test script in your composer.json

Now you can test what version of PHP is used for the commands Composer calls, e.g.

In my case, both of these use my default php script (which is version 7.4). So, while the 7.2 version is used to run Composer, the scripts called by Composer use the default command.

Now let’s add the platform setting as suggested in some of the answers

Does not change anything for the script execution:

Источник

How to install a specific version of package using Composer?

I am trying to install a specific version of a package using Composer. I tried composer install and composer require but they are installing the latest version of the package. What if I want an older version?

composer set php version

9 Answers 9

composer require vendor/package:version

composer require refinery29/test-util:0.10.2

Add double quotes to use caret operator in version number.

composer set php version

composer set php version

As @alucic mentioned, use:

Related to question about version numbers, you can review Composer documentation on versions, but here in short:

1.2.3 is equivalent to >=1.2.3 =1.2.3

composer set php version

composer set php version

just use php composer.phar require

Also available with install.

composer set php version

Suppose you want to install Laravel Collective. It’s currently at version 6.x but you want version 5.8. You can run the following command:

A good example is shown here in the documentation: https://laravelcollective.com/docs/5.5/html

Of course, as the other answers point out you can run the following from the terminal:

composer set php version

I tried to require a development branch from a different repository and not the latest version and I had the same issue and non of the above worked for me 🙁

after a while I saw in the documentation that in cases of dev branch you need to require with a ‘dev-‘ prefix to the version and the following worked perfectly.

Curl can be used to download a specific version:

composer set php version

composer require package-name version-number

Example: composer require «laravel/tinker»: «^2.5»

Источник

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, здесь указываем нужные нам файлы с классами и функциями.
Структура библиотеки:

Источник

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

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