Quantcast
Channel: LampJunkie.com - Everything related to Linux, PHP, MySQL, Apache, AJAX, Symfony and more
Viewing all articles
Browse latest Browse all 10

Writing Custom PHP Extensions to Speed Up Applications

$
0
0

Sometimes you may come across a situation where a core piece of your PHP is doing some sort of intensive algorithm or something else which is just taking way to long.

Recently I had this problem with an application which I was developing. Essentially I was redesigning an existing application that needed to be able to handle millions of requests every day. Inside of the original application was a core utility class that needed to encrypt query string parameters using a key based caesar cipher. The existing code was as optimized as it could be within PHP, but there were serious issues when we needed to encrypt 10+ links per page view. The average time was somewhere in the range of ~300ms just to run the encryption. Inside the encryption method was a loop that went through each character of a query string to convert it to it’s ASCII code and rotate those codes to perform the encryption.

This was one of those times when PHP really showed it’s weaknesses for intense “calculations”. After thinking about the problem for awhile, I decided to first convert the encryption/decryption methods to C++ and just use PHP’s exec() function to call the compiled C++ code. This worked, but just felt a little too weird…

After thinking about the problem some more, it hit me…how about I just convert the program to a custom PHP Extension! So then the journey of trying to find documentation and tutorials on how to do this began. After a few days I was able to write an extension and install it within PHP. Basically I designed the extension so that it exposed those encryption/decryption methods within a static class that can be used from any application on the server. The final results were that it took less than 1ms to encrypt all the querystrings in one shot. Much better!

Using this new found knowledge I was able to take another core class which used PHP’s Extended Reflection API to parse annotations within the docblocks of database model classes to map them to their respective tables and columns.

Once you understand how to use the Zend Engine’s internal API to build your custom extensions, the possibilities are endless. At that point it’s a trivial matter to convert your PHP code to C and compile your extension. But, figuring out where to find tutorials, etc on how to do this is the biggest hurdle to get over.

Here are some resources to get you started in the right direction:


Viewing all articles
Browse latest Browse all 10

Trending Articles