DEV Community

Cover image for Write a PHP library supports PHP 5.6 to 8.1
Ash Wu
Ash Wu

Posted on • Edited on

Write a PHP library supports PHP 5.6 to 8.1

Yes, you heard it right. We need to write a PHP library that supports from PHP 5.6 to PHP 8.1

There are still people out there using EOL PHP versions and we still want them to be able use our package.

Things that needs to be done needs to be done. Let's get to it.

The Code

Actually writing the code itself is probably the easiest part. You just don't use the fancy new stuff and stick to the old way.

I run two tools for this - php-cs-fixer on PHP 5.6 and the built-in syntax checker(php -l).

There's an existing Github Action prestashop/github-action-php-lint which handles this for you.

A full example of these two checks can be found here

The Tests

Writing the code is easy, but writing the tests is not. PHPUnit does not support old PHP versions and you can't use the latest PHP version with old PHPUnit version due to syntax issues.

Yaost/PHPUnit-Polyfills came to rescue. With just tiny adjustments to your tests, this can make your tests run across PHPUnit 4.8~9.x and PHP 5.4+

The CI

We also want to run tests for different versions automatically so we don't have to manually tests everything.

The official PHPUnit & composer Github Action didn't play well with old PHP versions.

I found shivammathur/setup-php did a better job on supporting old PHP versions, and you don't have to worry about the composer & extension compatibility, it handles those for you.

Here's a full example that you can run a matrix of PHP versions for your tests.

Wrap Up

Writing a PHP library that supports from PHP 5.6 to PHP 8.1 is not as hard as I imagine at the very beginning. PHP handles backward-compatibility very well. PHPUnit took me most of the time to figure out. Hopefully there're already a tool for that. I am not alone.

Hope this helps someone out there, trying to do the same thing.

Top comments (0)