1

Is there any way to require a dependency in composer.json only if a condition is fulfilled?

Typically, I'd like to use Guzzle 6 if the PHP version is high enough, otherwise do nothing. The library will handle a fallback if you don't have guzzle.

I know you can use "some/dependency": "^1.0 || ^2.0", which will choose the latest major that fits your other requirements. What I'm looking for is something like:

"some/dependency": "nothing || ^2.0"

1 Answer 1

1

You cannot do this directly as constraints in your composer.json. However you can achieve this by creating bridge package, which may define different dependencies for different versions, which could have different requirements.

So you can create me/guzzle-wrapper package and:

  1. Tag 1.0.0 version with composer.json:

    {
        "name": "me/guzzle-wrapper",
        "require": {
            "php": "<5.5",
        }
    }
    
  2. Tag 2.0.0 version with composer.json:

    {
        "name": "me/guzzle-wrapper",
        "require": {
            "php": ">=5.5",
            "guzzlehttp/guzzle": "^6.3"
        }
    }
    

So instead requiring guzzlehttp/guzzle directly, you can use this meta package - depending on your PHP version Composer will install 2.0.0 which requires Guzzle, or 1.0.0 which does not require anything.

But if your package is able to work without Guzzle, maybe you should move this requirement to suggest section?

Sign up to request clarification or add additional context in comments.

2 Comments

I think it's a good solution 👌 I'd rather keep everything in one repository but I'll think about it. At first, I thought about having 2 separate package and requiring a virtual package (like httplug does) but it felt very over engineered ^^ Thanks!
By the way, Jordi (maker of composer) confrmed over email that this would be the best solution 🚀

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.