2

I would like my composer.json to tell composer to install 1 version of a library if the system runs php7.x and another if the system runs on php8.x

The reason is that the 1.x versions of the library are compatible with php7 and 2.x versions only with php8. Like so:

if:{php: ^7, require:{mylib:^1.0}}
else:{php: ^8, require{mylib:^2.0}}

That would be great.
Some of our customers can not switch their servers to php8 so fast for various reasons but we would like to move on.

3
  • 2
    But that should be resolved by composer itself I think. E.g. "require": {"mylib": "*"}, and "mylib/composer.json" must contain information about PHP compatibility.
    – Justinas
    Commented Nov 15, 2022 at 13:34
  • 1
    @Justinas Letting Composer decide is good advice, but specifying * is not - you'll get in a mess if the library author releases version 3 with changes that aren't compatible with your code. Much better to always list the versions you've actually confirmed will work.
    – IMSoP
    Commented Nov 15, 2022 at 14:11
  • @IMSoP Yes, I know, comment idea was to tell that composer already handles that. And your answer deeply answers it
    – Justinas
    Commented Nov 15, 2022 at 16:06

1 Answer 1

6

The Composer version constraint syntax supports multiple constraints joined with || to represent "logical OR". This lets you write constraints like "either 1.x above 1.5, or 2.x above 2.1":

{
    "require": {
        "somevendor/somelib": "^1.5 || ^2.1"
    }
}

When someone runs composer update, Composer will then install the highest version available that satisfies both this constraint and the constraints specified by the library itself and anything else being installed.

As long as the 2.x releases of the library state in their composer.json that they require PHP 8, they won't be installed under PHP 7, and a 1.x release will be chosen instead.

Obviously, it's up to you to make sure that your code is actually compatible with both versions of the library, e.g. by regularly running tests on both versions.

Not the answer you're looking for? Browse other questions tagged or ask your own question.