对于php开发人员来说,写php扩展好像是一个很高级的东西。其实只是我们没有去接触,或者工作中根本没用到,所以感觉很高级。下面的例子,就是让你用5分钟,来编写你人生的第一个php扩展-hello word!
我们先假设业务场景,是需要有这么一个扩展,提供一个叫helloword的函数,他的主要作用是返回一段字符。(这个业务场景实在太假,大家就这么看看吧)对应的PHP代码可能是这样:
1 | function helloword( $str ){ |
3 | $result = 'helloword!' . $str ; |
第一步,生成代码 PHP为了扩展开发的方便,提供了一个类似代码生成器的工具ext_skel,具体可以参见说明。 首先我们创建一个文件helloword.skel,它的内容为
1 | string helloword(string str) |
就是告诉ext_skel这个东西,我们要做的扩展里面有个函数叫helloword。然后执行
1 | cd MooENV/src/php-5.3.8/ext/ |
3 | ./ext_skel --extname=helloword --proto=helloword.skel |
这时候,helloword这个扩展的代码框架就已经出来了。
第二步,修改配置 然后修改config.m4文件将10、11、12三行最前面的dnl删除掉,就是将
1 | dnl PHP_ARG_WITH(helloword, for helloword support, |
3 | dnl Make sure that the comment is aligned: |
5 | dnl [ --with-helloword Include helloword support]) |
修改为
1 | PHP_ARG_WITH(helloword, for helloword support, |
3 | Make sure that the comment is aligned: |
5 | [ --with-helloword Include helloword support]) |
第三步,实现功能 修改源码helloword.c文件 找到将helloword这个函数修改为
1 | PHP_FUNCTION(helloword) { |
5 | int argc = ZEND_NUM_ARGS(); |
11 | if (zend_parse_parameters(argc TSRMLS_CC, "s" , &str, &str_len) == FAILURE) return ; |
13 | str_len = spprintf(&result, 0, "helloword! %s" , str); |
14 | RETURN_STRINGL(result, str_len, 0); |
第四步,编译扩展 保存后,开始编译
1 | /usr/local/php/bin/phpize |
2 | ./configure --with-php-config=/usr/local/php/bin/php-config |
第五步,添加扩展 这时候,一切顺利的话,该扩展已经在modules/helloword.so这个位置了。下面就是将这个扩展加入到PHP中去,让我们PHP程序可以调用到。
1 | vim /usr/local/php/lib/php.ini |
extension=/usr/local/php/ext/helloword.so #在php.ini文件最后增加这一行
#重启PHP服务
写一个简单的寂寞代码helloword.php,内容如下:
3 | helloword( '这就是我的第一个php扩展,实在太简单了!' ); |
结果:
![RV`~OQG]KP0PH]VV2_}$T)2](http://www.39gs.com/wp-content/uploads/2015/08/RVOQGKP0PHVV2_T2-300x20.png)
文章发布在我的个人小站(拖鞋小站): http://www.39gs.com/archive/152.html 多多关照!