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