PHP为我们提供了生成基本代码的工具 ext_skel。这个工具在PHP源代码的./ext目录下。
1
2
|
$
cd
php_src
/ext/
$ .
/ext_skel
--extname=fish
|
extname参数的值就是扩展名称。执行ext_skel命令后,这样在当前目录下会生成一个与扩展名一样的目录。
在ext 目录下生成了fish 文件夹
➜ ext cd fish
➜ fish ll
total 64
drwxr-xr-x 11 yuxuefeng staff 352 7 2 21:41 .
drwxr-xr-x@ 79 yuxuefeng staff 2528 7 2 21:41 ..
-rw-r--r-- 1 yuxuefeng staff 398 7 2 21:41 .gitignore
-rw-r--r-- 1 yuxuefeng staff 5 7 2 21:41 CREDITS
-rw-r--r-- 1 yuxuefeng staff 0 7 2 21:41 EXPERIMENTAL
-rw-r--r-- 1 yuxuefeng staff 2024 7 2 21:41 config.m4
-rw-r--r-- 1 yuxuefeng staff 341 7 2 21:41 config.w32
-rw-r--r-- 1 yuxuefeng staff 5066 7 2 21:41 fish.c
-rw-r--r-- 1 yuxuefeng staff 496 7 2 21:41 fish.php
-rw-r--r-- 1 yuxuefeng staff 2284 7 2 21:41 php_fish.h
drwxr-xr-x 3 yuxuefeng staff 96 7 2 21:41 tests
config.m4的作用就是配合phpize工具生成configure文件。
configure文件是用于环境检测的。检测扩展编译运行所需的环境是否满足。现在我们开始修改config.m4文件。
打开,config.m4文件
1)其中,dnl 是注释符号。
2)如果你所编写的扩展依赖其它的扩展或者lib库 用PHP_ARG_ENABLE (静态编译)
如果你所编写的扩展不依赖其它的扩展或者lib库 用PHP_ARG_WITH(动态编译)
把多余的注释都删除:
2 PHP_ARG_ENABLE(fish, whether to enable fish support,
3 Make sure that the comment is aligned:4 [ --enable-fish Enable fish support])
5
6 if test "$PHP_FISH" != "no"; then
7
8 PHP_NEW_EXTENSION(fish, fish.c, $ext_shared,, -DZEND_ENABLE_STATIC_TSRMLS_CACHE =1)
9 fi
修改fish.c文件。实现fish方法。
找到PHP_FUNCTION(confirm_fish_compiled),在其上面增加如下代码:
1
2
3
4
5
6
|
PHP_FUNCTION(fish)
{
zend_string *strg;
strg = strpprintf(0,
"hello word"
);
RETURN_STR(strg);
}
|
找到 PHP_FE(confirm_fish_compiled, 在上面增加如下代码:
1
|
PHP_FE(fish, NULL)
|
PHP_FE(fish, NULL)
PHP_FE(confirm_fish_compiled, NULL) /* For testing, remove la ter. */
PHP_FE_END /* Must be the last line in fish_functions[] */
};
编译:
/usr/local/php7.2/bin/phpize
./configure --with-php-config=/usr/local/php7.2/bin/php-config
make && make install
vi /usr/local/php7.2/lib/php.ini
[fish]
extension_dir=/usr/local/php7.2/lib/php/extensions/no-debug-non-zts-20160303
extension = fish.so
php -m 就能看到fish扩展了
比如PHP的安装路径为:/usr/local/php7,则此目录的主要结构:
|---php7
| |---bin //php编译生成的二进制程序目录
| |---php //cli模式的php
| |---phpize
| |---php-config
| |---...
| |---etc //一些sapi的配置
| |---include //php源码的头文件
| |---php
| |---main //PHP中的头文件
| |---Zend //Zend头文件
| |---TSRM //TSRM头文件
| |---ext //扩展头文件
| |---sapi //SAPI头文件
| |---include
| |---lib //依赖的so库
| |---php
| |---extensions //扩展so保存目录
| |---build //编译时的工具、m4配置等,编写扩展是会用到
| |---acinclude.m4 //PHP自定义的autoconf宏
| |---libtool.m4 //libtool定义的autoconf宏,acinclude.m4、libtool.m4会被合成aclocal.m4
| |---phpize.m4 //PHP核心configure.in配置
| |---...
| |---...
| |---php
| |---sbin //SAPI编译生成的二进制程序,php-fpm会放在这
| |---var //log、run日志