Enforcing a PHP Version for Installed Composer Packages

If your development and production environments don’t match you can easily get tripped up when the time comes to deploy to the live server. It’s not too uncommon for developers to find themselves working with one version of PHP and using another in an app or website’s final destination. If you use Composer to manage PHP packages it would be nice to be able to take this into account to avoid any nasty surprises post deployment. Thankfully Composer has this covered.

We can tell Composer what version of PHP we are supporting with our app/website by using the platform configuration in our composer.json file.

{
    "name": ".../...",
    "config": {
        "platform": {
            "php": "5.6.1"
        }
    },
    "require": {
        ...
    }
}

In this example we are faking the version of PHP to 5.6.1. This means that whenever we try and install or update a package with Composer the faked platform version of PHP will be taken into account rather than the version of PHP being used on the command-line we are running Composer from. This is really useful if our production environment uses a different setup to the one we are developing on. For example, you may be using an up to date version of PHP 7 locally, but deploy to a server still using 5.6.

Another way of setting this is from the command-line.

composer config platform.php 5.6.1

This will set the platform option in the composer.json file for us. In this example it would add PHP 5.6.1 to the JSON file just like in the previous example. You can also use the -g flag to set this globally.

On a Composer package platform requirements are added just like package dependencies. So for example, if we have a package that requires a minimum of PHP 7.1.0 the composer.json file would look like:-

{
    "name": ".../...",
    "require": {
        "php": "7.1.0"
    }
}

This is what Composer will use when installing and updating packages when our project has a platform configuration.

Note that when adding a minimum PHP requirement we add this as a dependency using the require key, whereas setting the platform setup uses platform under the config options.

When it comes to installing and updating packages you may at times want to ignore the platform requirements. For example, when adding or updating a dev dependency that will never be installed on the production environment. For this we can use the --ignore-platform-reqs flag.

composer update phpunit/phpunit --ignore-platform-reqs

Although using the platform configuration in composer.json might not catch all unsuitable packages when using Composer it should hopefully catch most incompatible code that could otherwise have found their way onto your production environment. This has been a life saver for me in the past and helped me avoid many headaches.

Related Content

Published on