Max
Max

Reputation: 2643

Conditional composer requirements depending on php version

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.

Upvotes: 2

Views: 305

Answers (1)

IMSoP
IMSoP

Reputation: 97648

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.

Upvotes: 6

Related Questions