构建PHP扩展 包括一下4个步骤
生成框架-》实现函数-》构建-》执行函数
构建一个扩展,需要的所有东西只有两样:PHP源码和PHP的可执行程序。因此,我们需要先准备好PHP源码和PHP运行环境。
生成框架
框架,即PHP扩展的框架,也称骨架。PHP提供了生成框架的工具,十分易用。
生成框架的步骤如下:
cd php源码根目录
cd ext
php ext_skel.php --ext 'goodbyeearth'
ext_skel是PHP提供的生成框架的工具,--ext 的值是扩展的名称。该命令的结果是在ext目录下创建了一个goodbyeearth目录,扩展框架的所有文件,都在这个目录下面。
实现函数
我们实现函数bye(),该函数没有参数和返回值,只打印一行字符串Goodbye Earth。
实现函数需要在2个文件中添加代码,文件在goodbyeearth目录下。
在php_goodbyeearth.h中的PHP_FUNCTION(confirm_goodbyeearth_compiled);下一行添加:
PHP_FUNCTION(bye);
在goodbyeearth.c中添加2段代码:
zend_function_entry goodbyeearth_functions[] = {
PHP_FE(confirm_goodbyeearth_compiled, NULL)
{NULL, NULL, NULL}
};
在以上代码段中添加:
zend_function_entry goodbyeearth_functions[] = {
PHP_FE(confirm_goodbyeearth_compiled, NULL) PHP_FE(bye, NULL)
{NULL, NULL, NULL}
};
在文件末尾编写函数的实现:
PHP_FUNCTION(bye)
{
php_printf("Goodbye Earth!
");
}
构建
构建是编译扩展的过程,包括以下步骤:
cd goodbyeearth
修改构建配置文件config.m4
将SEARCH_PATH的第3个路径改为扩展所在的路径,SEARCH_FOR的值是php_goodbyeearth.h
php环境目录/bin/phpize
./configure --with-php-config= php环境目录/bin/php-config --enable-goodbyeearth
make
make install
make会编译出goodbyeearth.so到goodbyeearth/modules下,make install会将goodbyeearth.so拷贝到php环境的扩展路径下,比如php环境目录/ext下。
执行函数
在php.ini中添加extension=goodbyeearth.so,重启php-fpm.
编写php脚本,比如test.php,内容如下:
<?php
echo bye();
运行php test.php,将输出:
Goodbye Earth!
则扩展里的函数bye()成功执行。