php自定义扩展开发

文章源于: https://www.bo56.com/php7%E6%89%A9%E5%B1%95%E5%BC%80%E5%8F%91%E4%B9%8Bhello-word/ ,经亲自验证,此文章代码只适用于php7

我们来生成一个say扩展,say扩展提供say方法,方法功能是返回hello world字符串

  • 利用ext_skel 生成扩展骨架
cd /data/src/php-7.2.25/ext //进入php源码扩展目录
./ext_skel --extname=say

extname参数的值就是扩展名称。执行ext_skel命令后,这样在当前目录下会生成一个与扩展名一样的目录。

  • 修改config.m4配置文件

config.m4的作用就是配合phpize工具生成configure文件。configure文件是用于环境检测的。检测扩展编译运行所需的环境是否满足。现在我们开始修改config.m4文件。

 $ cd ./say
 $ vim ./config.m4
dnl If your extension references something external, use with:
   
dnl PHP_ARG_WITH(say, for say support,
dnl Make sure that the comment is aligned:
dnl [  --with-say             Include say support])
 
dnl Otherwise use enable:
 
dnl PHP_ARG_ENABLE(say, whether to enable say support,
dnl Make sure that the comment is aligned:
dnl [  --enable-say           Enable say support])

其中,dnl 是注释符号。上面的代码说,如果你所编写的扩展如果依赖其它的扩展或者lib库,需要去掉PHP_ARG_WITH相关代码的注释。否则,去掉 PHP_ARG_ENABLE 相关代码段的注释。我们编写的扩展不需要依赖其他的扩展和lib库。因此,我们去掉PHP_ARG_ENABLE前面的注释。去掉注释后的代码如下:

dnl If your extension references something external, use with:
    
 dnl PHP_ARG_WITH(say, for say support,
 dnl Make sure that the comment is aligned:
 dnl [  --with-say             Include say support])
  
 dnl Otherwise use enable:
  
 PHP_ARG_ENABLE(say, whether to enable say support,
 Make sure that the comment is aligned:
 [  --enable-say           Enable say support])
  • 代码实现

修改say.c文件。实现say方法。
找到PHP_FUNCTION(confirm_say_compiled),在其上面增加如下代码:

PHP_FUNCTION(say)
{
        zend_string *strg;
        strg = strpprintf(0, "hello word");
        RETURN_STR(strg);
}

找到 PHP_FE(confirm_say_compiled, 在上面增加如下代码:

PHP_FE(say, NULL)

修改后的代码如下:

const zend_function_entry say_functions[] = {
     PHP_FE(say, NULL)       /* For testing, remove later. */
     PHP_FE(confirm_say_compiled,    NULL)       /* For testing, remove later. */
     PHP_FE_END  /* Must be the last line in say_functions[] */
};
  • 编译安装
/usr/local/php-7.2.25/bin/phpize
./configure --with-php-config=/usr/local/php-7.2.25/bin/php-config
make
make install

//进入扩展目录
-rwxr-xr-x 1 root root 151K Apr 14 11:32 mcrypt.so
-rwxr-xr-x 1 root root 3.5M Apr 14 11:21 opcache.a
-rwxr-xr-x 1 root root 1.9M Apr 14 11:21 opcache.so
-rwxr-xr-x 1 root root 104K Apr 14 11:28 pcntl.so
-rwxr-xr-x 1 root root 1.7M Apr 14 12:05 redis.so
-rwxr-xr-x 1 root root  31K May 31 10:14 say.so //自定义的扩展
  • 编辑php.ini文件
extension="say.so"
  • 命令行测试扩展
[root@ip /usr/local/php/lib]# /usr/local/php/bin/php -r "echo say();"
hello word[root@ip /usr/local/php/lib]#