WHY WRITE EXTENSIONS
There can be 3 valid reasons why you would want to write an extension:
- You want to add some functionality which is either not already present in PHP or can be improved.
- You have existing code in PHP which you want to optimize in speed and its memory usage by converting it into an extension.
- You have a great piece of code in PHP which you want to distribute/sell but do not want to give away the source.
There could be other reasons why you want to create an extension but by and large it would be related to one of the three reasons above.
DEVELOPMENT LANGUAGE
Traditionally PHP extensions are written in C++. There are two options for development:
- Using the Zephir language, which is a language specifically developed for writing PHP extensions. Its syntax is a mix of PHP and C and it takes care of a lot of housekeeping code and other stuff which you would have to deal with if you were to go the C++ way.
- Using PHP-CPP which is C++ library for creating PHP extensions. It provides a much better environment and framework than using barebones C++.
We will be using PHP-CPP for the rest of the blog series. This article assumes you are working in Linux. (I am using Linux Mint 17 Qiana). At a later stage I will add sections for Windows and FreeBSD Unix. It is also assumed that you are familiar with C++ programming.
SETUP PHP-DEV
Before you can make your extensions, you have to install the php5-dev package. To do that type
sudo apt-get install php5-dev
After installing php, you can run php-config from the shell prompt to find the directories in which the binaries and include files of PHP are installed.
If you try to compile PHP-CPP in the next section without installing php5-dev you will get compile errors about files or folders missing.
DOWNLOAD AND SETUP PHP-CPP
PHP-CPP requires g++ version 4.8.* or later. If you have an older compiler then you should update it first.
To get the latest version of PHP-CPP you can get it on github. But that is normally not a very stable version and you should only use it if you are already very familiar with PHP-CPP. The other option is to download a zip or tarball from their official site. This link contains both the options.
Make a directory and unzip the contents there. Then change working directory to the directory and run make and install.
sudo make install
On successful completion PHP-CPP should be ready for use.
Check /usr/lib to make sure that libphpcpp.so is present.
Check /usr/include to make sure phpcpp.h is present and the folder phpcpp has been created. This folder will contain all the header files of PHP-CPP.
Next: See Part 2 Your First Extension
Leave a Reply