资讯专栏INFORMATION COLUMN

一步步入门编写PHP扩展

helloworldcoding / 2171人阅读

摘要:加入的扩展一般在,如果找不到,请自行百度里面有很多文件。如果使用模式,需要重启,这样我们就应该有扩展,具体可以通过查看不会请自行百度编写代码既然说编写扩展可以提高运行效率,因此在这里,我们通过使用扩展和直接使用代码来进行对比,测试性能。

1、写在最前

  随着互联网飞速发展,lamp架构的流行,php支持的扩展也越来越多,这样直接促进了php的发展。

  但是php也有脚本语言不可避免的问题,性能比例如C等编译型语言相差甚多,所以在考虑性能问题的时候最好还是通过php扩展来解决。

  那么,怎么去做一个php扩展呢。下面从一个例子开始(本文章需要C基础)。

2、解决一个问题

  在一个系统中,如果经常要求一个数组的平方和,我们可以这么写。

function array_square_sum($data){
    $sum = 0;
    foreach($data as $value){
        $sum += $value * $value;
    }
    return $sum;
}
  实际执行的时候,php zend引擎会把这段话翻译成C语言,每次都需要进行内存分配。所以性能比较差。进而,基于性能上的考虑,我们可以编写一个扩展来做这个事情。

3、编写扩展

  构建一个扩展,至少需要2个文件。一个是Configulator文件,它会告诉编译器编译这个扩展至少需要哪些依赖库;第二个是实际执行的文件。

3.1 生成框架

  听起来很复杂,实际上有一个工具可以帮我们搞定一个扩展的框架。在php源代码里面有个工具ext_skel,他可以帮我们生成扩展框架。

liujun@ubuntu:~/test/php-5.5.8/ext$ ls ext_skel
ext_skel

  现在我们利用它生成扩展 array_square_sum。($表示提示符命令)

$ ./ext_skel --extname=array_square_sum
Creating directory array_square_sum
Creating basic files: config.m4 config.w32 .svnignore array_square_sum.c php_array_square_sum.h CREDITS EXPERIMENTAL tests/001.phpt array_square_sum.php [done].

To use your new extension, you will have to execute the following steps:

$ cd ..

$ vi ext/array_square_sum/config.m4

$ ./buildconf

$ ./configure --[with|enable]-array_square_sum

$ make

$ ./php -f ext/array_square_sum/array_square_sum.php

$ vi ext/array_square_sum/array_square_sum.c

$ make

Repeat steps 3-6 until you are satisfied with ext/array_square_sum/config.m4 and
step 6 confirms that your module is compiled into PHP. Then, start writing
code and repeat the last two steps as often as necessary.

  执行命令之后,终端告诉我们怎么去生产新的扩展。查看一下文件内容,会发现多了几个比较重要的文件config.m4, php_array_square_sum.h,array_square_sum.c,下面会一一叙述。

liujun@ubuntu:~/test/php-5.5.8/ext$ ll array_square_sum/
total 44
drwxr-xr-x 3 liujun liujun 4096 Jan 29 15:40 ./
drwxr-xr-x 80 liujun liujun 4096 Jan 29 15:40 ../
-rw-r--r-- 1 liujun liujun 5548 Jan 29 15:40 array_square_sum.c
-rw-r--r-- 1 liujun liujun 532 Jan 29 15:40 array_square_sum.php
-rw-r--r-- 1 liujun liujun 2354 Jan 29 15:40 config.m4
-rw-r--r-- 1 liujun liujun 366 Jan 29 15:40 config.w32
-rw-r--r-- 1 liujun liujun 16 Jan 29 15:40 CREDITS
-rw-r--r-- 1 liujun liujun 0 Jan 29 15:40 EXPERIMENTAL
-rw-r--r-- 1 liujun liujun 3112 Jan 29 15:40 php_array_square_sum.h
-rw-r--r-- 1 liujun liujun 16 Jan 29 15:40 .svnignore
drwxr-xr-x 2 liujun liujun 4096 Jan 29 15:40 tests/
3.2 配置文件config.m4
dnl PHP_ARG_WITH(array_square_sum, for array_square_sum support,
dnl Make sure that the comment is aligned:
dnl [ --with-array_square_sum Include array_square_sum support])

  去掉dnl

PHP_ARG_WITH(array_square_sum, for array_square_sum support,
Make sure that the comment is aligned:
[ --with-array_square_sum Include array_square_sum support])

  这是./configure时能够调用enable-sample选项的最低要求.PHP_ARG_ENABLE的第二个参数将在./configure处理过程中到达这个扩展的配置文件时显示. 第三个参数将在终端用户执行./configure --help时显示为帮助信息

3.3 头文件

  修改php_array_square_sum.h,把confirm_array_square_sum_compiled改成confirm_array_square_sum,这个为我们以后实际调用的函数名字,当然你也可以直接加入函数confirm_array_square_sum,而不删除confirm_array_square_sum_compiled。

PHP_FUNCTION(confirm_array_square_sum_compiled);

  该成

PHP_FUNCTION(array_square_sum);
3.3 源代码

  修改 array_square_sum.c,把confirm_array_square_sum_compiled改成confirm_array_square_sum,这个是注册这个扩展的函数,如果在3.2中直接加入了confirm_array_square_sum,在这一步也直接加入confirm_array_square_sum就可以了。

const zend_function_entry array_square_sum_functions[] = {

PHP_FE(confirm_array_square_sum_compiled,   NULL)       /* For testing, remove later. */
PHP_FE_END  /* Must be the last line in array_square_sum_functions[] */

};

  改成

const zend_function_entry array_square_sum_functions[] = {

PHP_FE(array_square_sum,    NULL)       /* For testing, remove later. */
PHP_FE_END  /* Must be the last line in array_square_sum_functions[] */

};

  然后最为关键的一个步骤,重写confirm_array_square_sum,这个时候只需要把confirm_array_square_sum_compiled重写成confirm_array_square_sum(3.1中没有删除confirm_array_square_sum_compiled,就需要加入confirm_array_square_sum就好了)。

PHP_FUNCTION(confirm_array_square_sum_compiled)

  重写为

PHP_FUNCTION(array_square_sum)
{

zval* array_data;
HashTable *ht_data;
int ret;
char* key;
uint index;
zval **pdata;
double sum = 0;

if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &array_data) == FAILURE) {
    return;
}   

ht_data = Z_ARRVAL_P(array_data);
zend_hash_internal_pointer_reset(ht_data);
while ( HASH_KEY_NON_EXISTANT != (ret = zend_hash_get_current_key(ht_data, &key, &index, 0)) ) { 
    ret = zend_hash_get_current_data(ht_data, &pdata);

    if( Z_TYPE_P(*pdata) == IS_LONG){
        sum +=  Z_LVAL_P(*pdata) *  Z_LVAL_P(*pdata);
    }else {
        RETURN_FALSE;
    }   
    zend_hash_move_forward(ht_data);
}   
zend_hash_internal_pointer_end(Z_ARRVAL_P(array_data));
RETVAL_DOUBLE(sum);

}

  php是一个弱类型语言,他的数据都存在结构体zval里面(具体请看更加专业资料,如"php扩展开发.pdf")。

typedef union _zval {

long lval;
double dval;
struct {
    char *val;
    int len;
} str;
HashTable *ht;
zend_object_value obj;

} zval;

  为了获得函数传递的参数,可以使用zend_parse_parameters()API函数。下面是该函数的原型:

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

 zend_parse_parameters()函数的前几个参数我们直接用内核里宏来生成便可以了,形式为:ZEND_NUM_ARGS() TSRMLS_CC,注意两者之间有个空格,但是没有逗号。从名字可以看出,ZEND_NUM_ARGS()代表这参数的个数。后面紧跟着是常见的参数类型(和C语言的printf类似),后面就是常见的参数列表。
 下表列出了常见的参数类型。

参数类型 对象C类型 说明
l long 整数
b bool 布尔
s char* 字符串
d double 浮点数
a array(zval*) 数组
z zval* 不确定性zval

  此外数组是一个大型的hashtable来实现的,所以zend_hash_get_current_key可以遍历数组,使用宏Z_LVAL_P(zval*)获得实际的值。最终可以将结果放入到sum里面。RETVAL_DOUBLE(value)也是一个宏,返回结果为double,值则为value,具体可以参见" php扩展开发.pdf".

  最终完成了这个主函数的开发。

3.4 生成configure文件

  然后执行 ~/php/bin/phpize  

/home/liujun/php/bin/phpize
Configuring for:
PHP Api Version: 20121113
Zend Module Api No: 20121212
Zend Extension Api No: 220121212

  可以发现array_square_sum出现可执行脚本configure。

3.5 编译

  编译的时候最好带上php-config PATH,因为系统默认的php-config-path可能不是你目前使用的php路径。

liujun@ubuntu:~/test/php-5.5.8/ext/array_square_sum$ ./configure --with-php-config=/home/liujun/php/bin/php-config

  编译如果成功,终端会有如下提示:

creating libtool
appending configuration tag "CXX" to libtool
configure: creating ./config.status
config.status: creating config.h
config.status: config.h is unchanged

  查看array_square_sum目录的module目录,会发现里面生成array_square_sum.so,这个就是我们需要的扩展。

liujun@ubuntu:~/test/php-5.5.8/ext/array_square_sum$ ls modules/
array_square_sum.la array_square_sum.so
4、使用扩展
4.1、配置扩展

  修改php的配置php.ini,加入一下配置内容。

[array_square_sum]
extension=array_square_sum.so
4.2、加入module

  php的扩展一般在 $PHP_PATH/lib/php/extensions/no-debug-non-zts-yyyymmdd,如果找不到,请自行百度or Google. 里面有很多.so文件。 

  把3.5生产的array_sum_square.so拷贝进去即可。

  如果使用fastcgi模式,需要重启php,这样我们php就应该有扩展array_square_sum,具体可以通过查看phpinfo(不会请自行百度orGoogle).

4.2、编写代码

  既然说编写扩展可以提高运行效率,因此在这里,我们通过使用扩展和直接使用php代码来进行对比,测试性能。多次实验可以减少误差,所以进行2000次对100000个数字求平方和。代码如下:

$data = array();
$max_index = 100000;
$test_time = 2000;
for($i=0; $i<$max_index; $i++){
    $data[] = $i; 
}   

$php_test_time_start = time();
php_test($test_time, $data);
$php_test_time_stop = time();
echo "php test ext time is ". ($php_test_time_stop - $php_test_time_start). "
";

$c_test_time_start = time();
c_test($test_time, $data);
$c_test_time_stop = time();
echo "php test time is ". ($c_test_time_stop - $c_test_time_start). "
";

function php_test($test_time, $test_data){
    for($i=0; $i<$test_time; $i++){
        $sum = 0;
        foreach($test_data as $data){
            $sum += $data * $data;
        }   
    }   
}   

function c_test($test_time, $test_data){
    for($i=0; $i<$test_time; $i++){
        $sum = array_square_sum($test_data);
    }   
}
  测试结果如下:

liujun@ubuntu:~/php$ ~/php/bin/php test.php
php test ext time is 30
php test time is 2

   可以看到扩展要比直接使用php快15倍。随着业务逻辑变得更加复杂,这个差异化会越大。

 那么直接使用c语言来做这个事情呢。下面也给一个代码来测试下(测试条件完全一致):
include include include define TEST_TIME 2000 define MAX_INDEX 100000

int main()
{

int data[MAX_INDEX];
double sum = 0;

for(int i=0; i

}

  执行查看效果,可以看出直接使用C的时间只有0.261746,是使用C扩展的13.09%,是直接使用php的0.87%。当然如果涉及到IO等复杂操作,C/C++会比php快上万倍(测试过)。 

liujun@ubuntu:~/php$ g++ test.cpp -O2 -o test
liujun@ubuntu:~/php$ ./test
total time is 0.261746
sum time is 36207007178615872.000000

  因此,在实际对性能要求非常高的服务,如索引、分词等,可以使用C做一套底层服务,php去进行封装调用。 

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/50185.html

相关文章

  • 步步入门编写PHP扩展

    摘要:加入的扩展一般在,如果找不到,请自行百度里面有很多文件。如果使用模式,需要重启,这样我们就应该有扩展,具体可以通过查看不会请自行百度编写代码既然说编写扩展可以提高运行效率,因此在这里,我们通过使用扩展和直接使用代码来进行对比,测试性能。 1、写在最前 随着互联网飞速发展,lamp架构的流行,php支持的扩展也越来越多,这样直接促进了php的发展。 但是php也有脚本语言不可避...

    Mike617 评论0 收藏0
  • 步步入门编写PHP扩展

    摘要:加入的扩展一般在,如果找不到,请自行百度里面有很多文件。如果使用模式,需要重启,这样我们就应该有扩展,具体可以通过查看不会请自行百度编写代码既然说编写扩展可以提高运行效率,因此在这里,我们通过使用扩展和直接使用代码来进行对比,测试性能。 1、写在最前 随着互联网飞速发展,lamp架构的流行,php支持的扩展也越来越多,这样直接促进了php的发展。 但是php也有脚本语言不可避...

    DrizzleX 评论0 收藏0
  • 成为PHP程序员的正确姿势

    摘要:因为这对于一个刚参加工作的工程师来说,这有可能就是一月和一个月的区别了。多编写网站编程说到底其实也就是一门手艺,就对于智商差不多的程序员来说,技艺的高超程度往往就在于练的多少了。 利益相关:以下的所有文字都是仅代表个人观点,不代表全组织的利益。 本人就是一大三狗,自学PHP时间已经快两年了,感觉自己还是一个入门级的选手。说说自己是如何一步步走过来的。 1. 官方文档 对,我还是坚...

    mikyou 评论0 收藏0
  • 2.准备—本地工具

    摘要:没错,我想这正是我们大多数人学习新东西不断探索向前时使用最多的工具了。开发工具推荐是公司旗下一款开发工具。简称是在年月日开发者大会上正式宣布一个运行于和之上的,针对于编写现代和云应用的跨平台源代码编辑器,可在桌面上运行,并且可用于,和。 ...

    fjcgreat 评论0 收藏0
  • 5分钟PHP扩展开发快速入门

    摘要:简单点,先来实现一个扩展的。接下来我们将使用它来生成我们的扩展的基本骨架。注意不要添加任何分号。有兴趣的同学可以自行研究一下静态编译是什么鬼在扩展目录中执行命令。一定要在扩展的目录执行才有效,否则将得到一个错误提示。 简单点,先来实现一个PHP扩展的hello world。注意,以下所有操作都是基于linux系统(推荐centos和ubuntu, Mac系统应该类似 ),PHP5.5以...

    RobinTang 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<