PHP Kernel Learning--Creating PHP extensions
Start looking at the PHP kernel for a while, and now start learning to summarize, today to summarize how to create your own PHP extension.
My environment is as follows:
System: Ubuntu 14.04
PHP Version: 5.5.19
Reference excerpt: Extending your PHP with C/C + +
One of the main reasons PHP has been successful is that it has a large number of available extensions. No matter what the web developer needs, this requirement is most likely to be found in the PHP release package. The PHP release package includes many extensions that support various databases, graphics file formats, compression, and XML technology extensions.
The introduction of the extended API has made PHP3 progress, and the extended API mechanism makes it easy for the PHP development community to develop dozens of extensions. Now, two versions have passed, and the API is still very similar to PHP3. The main idea of the extension is to hide PHP's internal mechanisms and the scripting engine itself from the extension writer as much as possible, just to familiarize the developer with the API.
There are two reasons to write a php extension yourself. The first reason is that PHP needs to support a technology that she has not yet supported. This usually includes wrapping some off-the-shelf C libraries to provide PHP interfaces. For example, if a database called Foobase is already in the market, you need to build a PHP extension to help you invoke the C function library from PHP foobase. The job may be done by just one person and then shared by the entire PHP community (if you want to). The second not-so-common reason is that you need to write some business logic from the considerations of performance or functionality.
Suppose you are developing a Web site that requires a function that repeats the string n times. Here is an example written in PHP:
function util_str_repeat($string,$n){ $result= ""; for($i= 0;$i<$n;$i++){ $result.=$string; } return $result;} util_str_repeat("One", 3);//returns "Oneoneone".util_str_repeat("One", 1);//returns "One".
Suppose, for some strange reason, you need to call this function often, and pass it to a long string of functions and a large value n. This means that there is a considerable amount of string connection and memory reallocation in the script, which significantly slows down the execution of the script. If you have a function that allocates a large amount of memory more quickly to hold the result string and then repeats the $string n times, you do not need to allocate memory in each iteration of the loop.
The first step in establishing a function for an extension is to write a function definition file that defines the prototype of the function that the extension provides externally. In this example, the definition function has only one line of the function prototype Util_str_repeat ():
string util_str_repeat (stringint N)
The general format of a function definition file is a function line. You can define optional parameters and use a large number of PHP types, including: bool, float, int, array, and so on.
Save as Util.def file to php original code directory tree (that is, with the Ext_skel file in the same directory, my directory is/usr/share/php5/).
Then it is time to run the function definition file by extending the skeleton (skeleton) constructor. The constructor script is Ext_skel. Suppose you save the function definition in a file called Util.def, and you want to name the extension util, run the following command to build the extension skeleton:
sudo./ext_skel--extname=util--proto=util.def
After execution, I reported the following error here:
./ext_skel:1: Cd:can'T CD To/usr/lib/php5/skeletonCreating directory Utilawk: Cannot open/create_stubs (No suchfileor directory) Creating basic files:config.m4 config.w32. Svnignore util.c./ext_skel:216:./ext_skel:cannot Open/skeleton.c:no Suchfilephp_util.h./ext_skel:234:./ext_skel:cannot Open/php_skeleton.h:no SuchfileCREDITS./ext_skel:238:./ext_skel:cannot Open/credits:no SuchfileExperimental./ext_skel:242:./ext_skel:cannot Open/experimental:no Suchfiletests/001. Phpt./ext_skel:247:./ext_skel:cannot open/tests/001. Phpt:no suchfileutil.php./ext_skel:251:./ext_skel:cannot Open/skeleton.php:no SuchfileRM: Cannot remove ' function_entries ': No suchfileor directoryRM: Cannot remove ' function_declarations ': No suchfileor directoryRM: Cannot remove ' function_stubs ': No suchfileor directory [ Done]. To use your new extension and you'll have to execute the following steps:1. $ CD.2. $VIext/util/CONFIG.M43. $ ./buildconf4. $./configure--[with|enable]-util5. $ Make6. $./php-f ext/util/util.php7. $VIext/util/util.c8. $ MakeRepeat Steps3-6 untilYou is satisfied with ext/util/config.m4 Andstep6confirms that your module is compiled into PHP. Then, start Writingcode and repeat the LastSteps as often as necessary.
Obviously the/usr/lib/php5/skeleton path error, edit the Ext_skel file, change/usr/lib/php5/skeleton to/usr/share/php5/skeleton, Then remove the generated Util folder and execute the previous command again, following the successful prompt:
Creating directory utilcreating basic files:config.m4 config.w32. Svnignore util.c php_util.h CREDITS experimental te STS/001. PHPT util.php [ Done]. To use your new extension and you'll have to execute the following steps:1. $ CD.2. $VIext/util/CONFIG.M43. $ ./buildconf4. $./configure--[with|enable]-util5. $ Make6. $./php-f ext/util/util.php7. $VIext/util/util.c8. $ MakeRepeat Steps3-6 untilYou is satisfied with ext/util/config.m4 Andstep6confirms that your module is compiled into PHP. Then, start Writingcode and repeat the LastSteps as often as necessary.
The extension is then compiled in a statically compiled fashion. In order for the extension to be compiled, the CONFIG.M4 file under the extended directory util/needs to be modified. The extension does not package any external C libraries, you need to add support –enable-util configuration switches to the PHP compilation system (–with-extension switches are used for those extensions that require the user to specify the relevant C-Library path). Find the following:
is aligned:dnl [ --enable-util enable util support])
Remove the previous DNL and modify it to the following result:
is aligned:[ --enable-util enable util support])
Then modify the util.c file to find the following code:
php_function (util_str_repeat) {Char*str =NULL; intARGC =Zend_num_args (); intStr_len; LongN; if(Zend_parse_parameters (argc tsrmls_cc,"SL", &str, &str_len, &n) = =FAILURE)return; Php_error (e_warning,"Util_str_repeat:not Yet implemented");}
Modify it to the following code:
php_function (util_str_repeat) {Char*str =NULL; intARGC =Zend_num_args (); intStr_len; LongN; Char*result;/*Points to resulting string*/ Char*ptr;/*Points at the next location we want to copy to*/ intResult_length;/*Length of resulting string*/ if(Zend_parse_parameters (argc tsrmls_cc,"SL", &str, &str_len, &n) = =FAILURE)return; /*Calculate length of result*/Result_length= (Str_len *N); /*Allocate memory for result*/result= (Char*) Emalloc (result_length +1); /*Point at the beginning of the result*/ptr=result; while(n--) { /*Copy str to the result*/memcpy (PTR, str, str_len); /*Increment ptr to point at the next position we want to write to*/ptr+=Str_len; }
/*Null terminate the result. Always null-terminate your strings even if they is binary strings*/*ptr =' /'; /*Return result to the scripting engine without duplicating it*/Return_stringl (result, Result_length,0);}
The specific content inside, it is not here to say, then will slowly write.
Then it is compiled, installed. In the Util directory, the commands are as follows (commands may be required to add sudo):
phpize. /Configure make do testmakeinstall
Then configure the generated extension file, in the php5.5 version, into the/etc/php5/mods-available directory, create the Util.ini file, write the following:
Extension=util.so
Then enable util extension
sudo php5enmod util
Finally, restart PHP-FPM
sudo service php5-fpm restart
Create a PHP file, test it, and test the file as follows:
PHP for ($i$i$i+ +) {print$i) ; Print "\ n";}? >
The results of the implementation are as follows:
Craryprimitiveman Craryprimitiveman Craryprimitiveman Craryprimitiveman Craryprimitiveman CraryPrimitiveMan
This allows us to successfully create an extension that contains a simple PHP function.
Steal a Picture ~ ~
I'll be here today.
-
1 floor Kat Editor
-
Very good, thanks for sharing, are interested in writing books out of books?
-
Re: crazy primitive man
-
@ Kat Editor, the level is not enough ah ...