Using different code depending on the version of another dependency

Following situation:

  • Library X (maintained by me) depends on library Y version ^2.0.
  • For library Y, a newer major version 3 exists that is generally better.
  • Upgrading code built on top of Y 2 to Y 3 is straightforward, but requires a few adjustments to the existing code nonetheless.
  • Y is a dependency of X, so upgrading it would force users of X to upgrade, too, and thus also requires updating code that uses Y outside of X.

I'd like to make X installable with both Y 2 and Y 3. My approach would be to provide different versions of the code using Y and switch between the versions depending on the installed version, similar to C conditional compilation.


  • Is there a better approach to this?
  • How would I implement conditional code like that?
  • Any other comments or suggestions?


  • If X uses composer, then you may find versions of installed packages using composer's runtime API: