PHP Extension Development Series under Linux: two. A typical extended development

Source: Internet
Author: User
After reading the preface to some of the content, you should have a general understanding of PHP Extension development, some people may think that development is very cumbersome and complicated, in fact, this is not the case, this one we quickly into the role, the development of our first extension.

First, compile PHP

Before development, you need to prepare the PHP source code and compile, the process is as follows:

TAR-ZXVF PHP-5.3.9.TAR.GZCD php-5.3.9

I use php5.3.9, after decompression, we enter the PHP source directory, and then we directly compile and add PHP.ini:

./configure--prefix=/usr/local/webserver/php--enable-fastcgi--enable-fpm--enable-debugmake && make Installcp/home/soft/php-5.3.9/php.ini-development/usr/local/webserver/php/lib/php.ini

After compiling, I did not statically compile the other extensions, but I turned on debug, which is used later. And then modify the corresponding items in the php.ini, here is not the detail.

Now add PHP related to the environment variables, save a lot of work behind:

Vim/root/.bash_profile

I am using root, other different users to modify the corresponding user directory under the. bask_profile file, in the file after the path to add:/usr/local/webserver/php/bin/, similar to the following:

Path= $PATH: $HOME/bin:/usr/local/webserver/php/bin/

Environment variables are set, we look at the following PHP version:

OK, compile the work to finish, let's continue.

II. Typical development process

A typical extended development process such as:

Third, extended function definition

Define the extensions we want to complete first:

This extension has only one function, is to rewrite the PHP system function Ip2long (), to solve the Ip2long in 32-bit and 64-bit system under the different values of the problem (this issue is due to the 32-bit and 64-bit different shaping range, for specific reasons, Google).

Our new Ip2long fixed returns a 32-bit signed integer, ranging from 2147483648 to 2147483647, the same as a 32-bit system.

Our extension name is Myip and the function name is IP2LONG32

The extended features and names are OK, and are now being developed by process.

Iv. Formal Development

1. Build the development skeleton

First enter the source code extension directory:

Cd/home/soft/php-5.3.9/ext

Then understand the following PHP provides the extension skeleton tool Ext_skel build skeleton, Ext_skel use the following:

./ext_skel--extname=module [--proto=file] [--stubs=file] [--xml[=file]]           [--skel=dir] [--full-xml] [--no-help]  --extname=module   Module is the name of the Your extension (module name, which creates a subdirectory of the name in the current directory)  --proto=file       file Contains prototypes of functions to create (function prototype definition file)  --stubs=file       generate only function stubs in file  --xml              generate XML Documentation  to is added to Phpdoc-cvs--skel=dir directory         (set skeleton-generated directory, not set Default is Ext/extname)  --full-xml         generate XML documentation for a self-contained extension                     (not yet  Implemented)  --no-help          don ' t try to being nice and create comments in the code and                     helper functions to test if The module compiled (does not display various help notes in the generated code)

This time we are going to use two options,--extname=myip defines the name of the extension, and--proto=myip.pro is the function prototype that defines the extension, first we generate the extension function prototype file:

Vim Myip.pro

Add the following content:

int ip2long32 (string IP)

This means that there is a function in our extension, the return value is type int, and the input is string.

The following command is executed to generate the extended skeleton:

./ext_skel--extname=myip--proto=myip.pro

OK, at this time you will find in the current PHP extension directory generated a subdirectory Myip, into the Myip look:

CD MYIPLL

You will find a bunch of files generated, such as:

Now we can take the second step.

2. Modify CONFIG.M4

With regard to the functionality of the Config.m4 file, let's leave it in a later article that explains in detail and now only shows what to do.

Use Vim to edit config.m4:

Vim CONFIG.M4

Remove the DNL from the beginning of line 16 to 18, as follows:

The reasons for doing this are explained in the following article, where we exit directly and save CONFIG.M4 and proceed to the next step.

3. Encoding

The play comes, finally can enter the MYIP.C to carry on the function the code, cheers together!

Vim myip.c

Locate the location shown:

The diagram is the corresponding function generated by the extended skeleton tool based on the function prototypes we provide, here are a few points to note:

1. Php_function: is a macro defined by the PHP core, the same as zend_function, used to define the extension function, the actual generated function name is ZIF_IP2LONG32.

2. Zend_parse_parameters: Because PHP is a weakly typed language, and C is a strong type, it is necessary to use this function to receive the parameters that are passed into PHP, and to make some type conversion, the PHP variable to the C language can recognize the type.

The Zend_parse_parameters function is prototyped as follows:

zend_parse_parameters (int num_args tsrmls_cc, char *type_spec, ...);

Parameter description:

Num_args: The number of arguments passed to the function. The usual practice is to use the macro Zend_num_args (). TSRMLS_CC: Thread-safe, always pass TSRMLS_CC macros. Detailed: http://www.54chen.com/php-tech/what-is-tsrmls_cc.html Type_spec: The third parameter is a string that specifies the type of argument the function expects ... : List of variables that need to be updated with parameter values]

Type_spec is a formatted string, and its common meanings are as follows:

The type that the parameter represents

b Boolean

L Integer Integer type

D Floating point Float type

S string strings

R Resource Resources

A array of arrays

O Object instance

O object instance of a specified type specific types of objects

Z non-specific zval any type ~

Z zval** Type

f denotes function, method name

We will modify the function to read as follows:

Php_function (IP2LONG32) {         char *ip = NULL;         int argc = Zend_num_args ();         int Ip_len;          if (Zend_parse_parameters (argc tsrmls_cc, "s", &ip, &ip_len) = = FAILURE) {                 return;         }                  int32_t Ip_int32;         unsigned char ip1, IP2, IP3, IP4;                  SSCANF (IP, "%hhu.%hhu.%hhu.%hhu", &ip1, &ip2, &IP3, &IP4);         Ip_int32 = (int32_t) ((ip1 << 24) | (ip2 << 16) | (IP3 << 8) | IP4);         Return_long (Ip_int32); }

The function is complete, here is a return_long (Ip_int32) is very special, this is also the PHP kernel provides macros, for the return value to PHP, specify as follows:

Set return value and End Function set return value macro return type and parameter
Return_long (L) Retval_long (l) integer
Return_bool (b) Retval_bool (b) Boolean number (1 or 0)
Return_null () retval_null () NULL
Return_double (d) retval_double (d) floating point number
Return_string (S, DUP) retval_string (S, DUP) string. If the DUP is 1, the engine calls Estrdup () to repeat S, using the copy. If the DUP is 0, use s
Return_stringl (S, L, DUP) Retval_stringl (S, L, DUP) string value of length L. As with the previous macro, but because the length of s is specified, it is faster.
Return_true Retval_true Returns a Boolean value of TRUE. Notice that the macro has no parentheses.
Return_false Retval_false Returns a Boolean value of FALSE. Notice that the macro has no parentheses.
Return_resource (R) Retval_resource (r) resource handle.

The encoding is done, saved and exited, and then we can start compiling.

4. Compiling

Phpize./configure--with-php-config=/usr/local/webserver/php/bin/php-configmake && make install

After the compilation is complete, you will be prompted with the following:

Installing shared extensions:     /usr/local/webserver/php/lib/php/extensions/debug-non-zts-20090626/

Enter the directory to see if there are already myip.so, and finally we can modify php.ini load the so file

5. Modify PHP.ini

Cd/usr/local/webserver/php/libvim php.ini

Modify Extension_dir, and add extension = myip.so

Extension_dir = "/usr/local/webserver/php/lib/php/extensions/debug-non-zts-20090626/" extension = myip.so

Exit Save and restart PHP, if you are using PHPFPM, you can execute the following command:

KILL-USR2 ' Cat/usr/local/webserver/php/var/run/php-fpm.pid '

See if the extension is loading properly:

[root@tm977 lib]# Php-m|grep Myipmyip

The instructions are loaded properly, and finally we test the extension function!

6. Testing

Php-r "Var_dump (ip2long32 (' 192.168.1.1 '));" Int ( -1062731519) php-r "Var_dump (Ip2long (' 192.168.1.1 '));"  Int (3232235777)

As shown above, the IP2LONG32 output is a 32-bit signed integer, and the Ip2long output is a 64-bit unsigned integer, done!

V. Summary

With this one development example, is it really easy to actually develop an extension?

It's true, but it's not too early to be happy, actually developing a powerful extension is far from easy, and I'm going to go deeper into the next article while developing a more complex PHP core code.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.