PHP extension development series in Linux: 2. A typical extension development

Source: Internet
Author: User
Tags php source code prototype definition zts

 

After reading some of the content in the preface, you should have a general understanding of PHP extension development. Some people may think that development expansion is very complicated and complicated. In fact, this is not the case, in this article, we quickly enter the role and develop our first extension.

 

I. Compile PHP

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

tar -zxvf php-5.3.9.tar.gzcd php-5.3.9

I used php5.3.9. After decompression, we entered the PHP source code directory, and then we directly compiled and added 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 compilation is complete, I have not statically compiled other extensions, But I have enabled debug, which will be used later. Modify the corresponding items in PHP. ini. I will not go into detail here.

Now we can add PHP-related environment variables to save a lot of work:

vim /root/.bash_profile

I use root, and other users modify the contents in the corresponding user directory. in the bask_profile file, add/usr/local/webserver/PHP/bin/after the path in the file, as shown below:

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

After the environment variables are set, let's check the PHP version:

OK. The compilation is complete. Let's continue.

 

2. Typical Development Process

A typical extended development process is as follows:

 

3. Define extended functions

First, define the extended functions to be completed:

This extension has only one function, that is, rewrite the PHP system function ip2long (), solve the problem that ip2long has different values in 32-bit and 64-bit systems (this problem is caused by the difference in the integer range between 32-bit and 64-bit, please google for specific reasons ).

Our new ip2long fixed return 32-bit signed integer, range-2147483648 to 2147483647, the same as the 32-bit system.

Our extension is called myip, and the function name is ip2long32.

The extended functions and names are all OK and are now developed according to the process.

 

Iv. Formal Development

1. Generate a Development Skeleton

First, go to the source code extension directory:

 

cd /home/soft/php-5.3.9/ext

 

Next, let's take a look at the PHP extension skeleton tool ext_skel to generate a skeleton. The usage of ext_skel is as follows:

. /Ext_skel -- extname = module [-- proto = file] [-- stubs = file] [-- XML [= file] [-- skel = dir] [-- full-XML] [-- no-help] -- extname = module is the name of your extension (Module name, will create a subdirectory with this name in the current directory) -- proto = file contains prototypes of functions to create (function prototype definition file) -- stubs = file generate only function stubs in file -- XML generate xml documentation to be added to phpdoc-CVS -- skel = dir path to the skeleton directory (set the directory generated by the skeleton, if this option is not set, the default value is EXT/extname.) -- full-XML generate xml documentation for a self-contained extension (not yet implemented) -- no-help don't try to be nice and create comments in the Code and helper functions to test if the module compiled (various help comments are not displayed in the generated code)

This time, we will use two options: -- extname = myip, which defines the extension name, And -- proto = myip. Pro, which defines the extension function prototype. First, we will 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 int type and the input value is string.

Run the following command to generate the extension SKELETON:

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

OK. At this time, you will find that a sub-directory myip is generated under the current PHP extension directory. Go to myip and check it:

cd myipll

You will find that a bunch of files are generated, such:

Now we can proceed to step 2.

2. Modify config. M4

For more information about the functions of the config. M4 file, refer to the subsequent articles for details.

Use Vim to edit config. M4:

vim config.m4

Remove the DNL at the beginning of Lines 16 to 18, as shown below:

The specific reason for this is described in the following article. Here we exit and save config. M4 and continue to the next step.

3. Encoding

Let's cheer up!

vim myip.c

Find the following location:

The figure below shows the corresponding functions generated by the extension skeleton tool based on the function prototype we provide. Here are several notes:

1. php_function: a macro defined by the PHP core. It is the same as zend_function and is used to define extended functions. The actually generated function name is zif_ip2long32.

2. zend_parse_parameters: Because PHP is a weak type language and C is a strong type, you need to use this function to receive parameters passed in by PHP and perform type conversion, convert the PHP variable to a recognizable type in C.

The prototype of the zend_parse_parameters function is as follows:

zend_parse_parameters(int num_args TSRMLS_CC, char *type_spec, …);

Parameter description:

    • Num_args: number of parameters passed to the function. Generally, the macro zend_num_args () is used ().
    • Tsrmls_cc: thread security, always passing the tsrmls_cc macro. Details: http://www.54chen.com/php-tech/what-is-tsrmls_cc.html
    • Type_spec: The third parameter is a string that specifies the expected parameter type of the function.
    • ...: List of variables that need to be updated with parameter values]
    • Type_spec is a formatted string. Its common meanings are as follows:Parameter represents the typeb   BooleanL integerD floating pointS stringR ResourceA ArrayO object instance objectO object instance of a specified type object of a specific typeZ non-specific zval of any type ~Z zval ** typeF indicates the function and method name.

Modify the function 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 there is a special return_long (ip_int32), which is also a macro provided by the PHP kernel for returning values to PhP. The details are as follows:

Set the return value and end the function. Set the return value macro return type and parameters.
Return_long (l) retval_long (l) Integer
Return_bool (B) retval_bool (B) Boolean (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 DUP is 1, the engine will call estrdup () to duplicate S and use copy. If DUP is 0, S is used.
Return_stringl (S, L, DUP) retval_stringl (S, L, DUP) is a string value of L. Similar to the previous macro, but the speed is faster because the length of S is specified.
Return_true retval_true returns a Boolean value of true. Note that this macro has no parentheses.
Return_false retval_false returns the Boolean value false. Note that this macro has no parentheses.
Return_resource (r) retval_resource (r) Resource handle.

After encoding is complete, save and exit. Then we can start compiling.

4. Compile

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

If the compilation is complete, the following prompt will be displayed:

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

Go to the directory and check whether myip. So exists. If yes, we can modify PHP. ini to 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 phpfpm is used, run the following command:

kill -USR2 `cat /usr/local/webserver/php/var/run/php-fpm.pid`

Check whether the extension is loaded normally:

[root@tm977 lib]# php -m|grep myipmyip

It indicates that it has been loaded normally. Finally, let's test the extended function!

6. Test

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, ip2long32 outputs 32-bit signed integers, while ip2long outputs 64-bit unsigned integers!

 

V. Summary

Through this development example, do you think it is very easy to develop an extension?

Yes, but don't be happy too early. In fact, it is far from that simple to develop powerful extensions. I will continue to explore the following articles, learn more complex PHP core code while developing.

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.