Using PHP7 in PHP-FPM
You don’t need to port the entire site to PHP7 at once.
You can run PHP7 in PHP-FPM, and all the 7 code executes in there. The rest of the code runs in Apache. I used Apache2.4 and the mod_proxy_fcgi module.
The configuration to subject a folder to PHP7 looks like this:
<Directory /mnt/ad3/usr/local/www-domains/la.indymedia.org/public/admin/article/> <FilesMatch "\.php$"> SetHandler "proxy:unix:/var/php/www.php-fpm.socket|fcgi://localhost/" </FilesMatch> </Directory>
The way the site was structured, you’d have around three to twelve PHP files in there. Porting would involve making sure each PHP file was called, and could run.
Two Namespaces and an Autoloader
The old code was written without namespaces or an autoloader, because they didn’t exist in PHP4. I took advantage of namespaces to create a parallel set of classes that worked with both PHP5.6 and PHP7.
The existing classes were, mostly, compatible with PHP7, but some base classes and important classes were not. However, I couldn’t just go an alter the original classes, because fixes to the pages being ported could end up breaking code elsewhere.
So, instead, I created the SFACTIVE namespace, and then set up an autoloader to load these classes.
When a class broke, I’d copy it into the SFACTIVE directory, and edited it.
This way, you could continue to load the original classes, just like before, but replace the broken ones with the new version. Example:
$db = new DB();
Would be edited to:
$db = new \SFACTIVE\DB();
\SFACTIVE\DB was just a copy of DB, but fixed to work with PHP7.
DB used the mysql_* functions, but \SFACTIVE\DB used PDO.
I ended up rewriting around 20 off over 30 classes. Most of the fixes were minor, and involved:
- Changing the constructors to __construct()
- Replacing ereg_replace with preg_replace.
- Fixing unquoted strings.
I’ll get into this in detail next.