I recently wrote a post about updating to PHP 7.4. This is great! Exciting! Progress! But, it introduces some interesting challenges, especially once you’ve updated your host machine to a new version of PHP. Why? Well, for one, composer assumes that the version of PHP on the machine you are running on is the “right” version of PHP.
For instance, here’s a scenario where I updated my virtual machine to PHP 7.4 and I set PHP requirements inside my composer.json file to be PHP 7.4 BUT I had not yet updated my host machine to PHP 7.4:
Your requirements could not be resolved to an installable set of packages.
Problem 1
- Root composer.json requires php >=7.4 but your php version (7.3.14) does not satisfy that requirement.
You can also get into this problem in reverse, where you have updated your host machine to PHP 7.4 but not yet updated a project to PHP 7.4 (still at 7.2 or 7.3) and you accidentally do the upgrade.
There are a couple of ways composer impacts PHP version. Let’s dig into those!
PHP as a Dependency
Did you know you can add PHP as an a dependency right in the composer.json file? Well you can! And it’s definitely recommended, as it helps to make sure that you get the right version of other dependencies. If your project is running PHP 7.4 you want to make sure that all of your other dependencies work with PHP 7.4.
You add this just like any other dependency:
"require": {
"php": ">=7.4",}
Then you can just run composer update php --with-all-dependencies just like you would anything else.
Note: if you are receiving the error above about the compser.json requirements, sometimes this is an indication that you either SHOULD update your host PHP or that you should be working inside your VM. In my case, all I had to do to resolve that issue was to run the composer command inside the lando vm (so lando composer update [runs inside] vs. composer update [runs outside]).
PHP as a Platform Config
In the updating scenario I discussed previously, platform config will help make sure that your host PHP version and project PHP version stay in their lane.
"config": {
"platform": {
"php": "7.3"
}
},
By doing this, you will essentially make sure that even if you have PHP 7.4 on your host, this project will remain at PHP 7.3. Remember, "php": ">=7.3" as a requirement CAN MEAN PHP 7.4. So, by having "php": ">=7.3" as a requirement and "php": "7.3" as a platform config that will lock the project to PHP 7.3.
In Conclusion
This definition process is super useful when you have a large number of developers that aren’t working in a consistent environment (e.g. a common VM config). Any time you have folks that have the potential for variable PHP configs between machines, these additions to your composer.json fill will hopefully ensure a more stable composer experience.
Dependency trees can be massive, and with the upcoming Drupal 10 release PHP 8.1 could have a significant impact on your project.