您的位置:首页 > 编程语言 > PHP开发

写一个PHP扩展

2015-11-25 16:45 585 查看
在PHP开发的过程中,有时候为了提高性能,需要选择扩展的方式去实现,本文简单介绍怎么开发一个简单的PHP扩展,解开PHP扩展开发的神秘面纱

环境:PHP 5.6.13 debian7.7



第一步:建立扩展骨架

cd /download/src/php-5.6.13/ext (这里是我的php5.6.13的源码包的解压地址)

./ext_skel –extname=xiami_ext

第二步:修改编译参数

cd php-5.6.13/ext/xiami_ext

vi config.m4

去掉

PHP_ARG_ENABLE(xiami_ext, whether to enable xiami_ext support,

[ --enable-xiami_ext Enable xiami_ext support])

两行前面的dnl

修改后为:

复制代码 代码如下:

dnl Otherwise use enable:

PHP_ARG_ENABLE(xiami_ext, whether to enable xiami_ext support,

dnl Make sure that the comment is aligned:

[ --enable-xiami_ext Enable xiami_ext support])

第三步:编写代码

vim php_xiami_ext.h

在 PHP_FUNCTION(confirm_xiami_ext_compiled); 后面新增一行:PHP_FUNCTION(hello);

添加后为:

PHP_FUNCTION(confirm_xiami_ext_compiled); /* For testing, remove later. */

PHP_FUNCTION(hello);

然后

vim xiami_ext.c

在PHP_FE(confirm_xiami_ext_compiled, NULL) 后面添加 PHP_FE(hello, NULL)

添加后为:

复制代码 代码如下:

zend_function_entry xiami_ext_functions[] = {

PHP_FE(confirm_xiami_ext_compiled, NULL) /* For testing, remove later. */

PHP_FE(hello, NULL) /* For testing, remove later. */

PHP_FE_END /* Must be the last line in xiami_ext_functions[] */

};

在文件最后面增加如下代码:

复制代码 代码如下:

PHP_FUNCTION(hello)

{

char *arg = “This my first extention!”;

int len;

char *strg;

len = spprintf(&strg, 0, “%s\n”, arg);

RETURN_STRINGL(strg, len, 0);

}

第四步:编译代码


复制代码 代码如下:

cd php-5.6.13/ext/xiami_ext
/usr/local/php/bin/phpize

./configure –with-php-config=/usr/local/php/bin/php-config

make

make install

我的PHP安装路径为:/usr/local/php

这个时候会生成一个文件
/usr/local/php/lib/php/extensions/no-debug-non-zts-20131226/xiami_ext.so
编辑PHP配置文件php.ini,添加扩展:

vim php.ini

在[PHP]模块下增加:extension = xiami_ext.so

[xiami_ext]

extension = xiami_ext.so

第五步:检查安装结果

1. 重启apache或者php-fpm

2. /usr/local/php/bin/php -m |grep xiami_ext 看下是否有包含xiami_ext扩展。

第六步:执行测试代码

在网站根目录创建test.php

vim test.php

代码内容如下

<?php

echo hello();

?>

执行后结果为:This my first extention!

如果你能顺利完成以上几步,恭喜你完成了第一个扩展。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: