PHP扩展开发环境与初始设置
运行环境设定为 CentOS 5.5 操作系统,PHP 版本号为 5.2.14。
首先执行构建扩展基础结构的操作。
进入 PHP 源码目录下的扩展文件夹:cd php-5.2.14/ext
调用 ext_skel 脚本生成名为 laiwenhui 的扩展项目:./ext_skel –extname=laiwenhui
接下来调整编译相关的参数配置。
切换至新生成的扩展目录:cd php-5.2.14/ext/laiwenhui
编辑配置文件:vi config.m4
需要移除注释标记以启用该扩展的支持选项。
原代码片段如下:PHP_ARG_ENABLE(laiwenhui, whether to enable laiwenhui support,
[ --enable-laiwenhui Enable laiwenhui support])
将上述两行开头的 dnl 注释符删除。
修改完成后的状态如下所示。
dnl Otherwise use enable:
PHP_ARG_ENABLE(laiwenhui, whether to enable laiwenhui support,
dnl Make sure that the comment is aligned:
[ --enable-laiwenhui Enable laiwenhui support])
随后开始编写具体的扩展逻辑代码。
打开头文件进行编辑:vim php_laiwenhui.h
在现有函数声明 PHP_FUNCTION(confirm_laiwenhui_compiled); 之后添加新行:PHP_FUNCTION(test);
添加后的头文件内容示例如下。
PHP_FUNCTION(confirm_laiwenhui_compiled); /* For testing, remove later. */
PHP_FUNCTION(test);接着处理实现文件。
打开源文件进行编辑:vim laiwenhui.c
在函数列表条目 PHP_FE(confirm_laiwenhui_compiled, NULL) 之后追加 PHP_FE(test, NULL)
添加后的代码片段如下。
zend_function_entry laiwenhui_functions[] = {
PHP_FE(confirm_laiwenhui_compiled, NULL) /* For testing, remove later. */
PHP_FE(test, NULL) /* For testing, remove later. */
{NULL, NULL, NULL} /* Must be the last line in laiwenhui_functions[] */
};在文件末尾补充具体的函数实现代码。
PHP_FUNCTION(test)
{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.2.6/ext/laiwenhui
执行 phpize 脚本初始化构建环境:/opt/module/php/bin/phpize
配置编译参数,指定 php-config 路径:./configure –with-php-config=/opt/module/php/bin/php-config
执行编译命令:make
执行安装命令:make install
本例中 PHP 的安装根路径设置为:/opt/module/php
编译安装完成后,将在以下路径生成动态链接库文件 /opt/module/php/lib/php/extensions/no-debug-non-zts-20060613/laiwenhui.so
接下来编辑 PHP 主配置文件以加载该扩展。
打开配置文件:vim php.ini
在 [PHP] 模块配置段内新增一行:extension = laiwenhui.so
;extension=php_zip.dll
extension = laiwenhui.so
同时需修正 extension_dir 指向正确的扩展目录。
extension_dir = “/usr/local/php/lib/php/extensions/no-debug-non-zts-20060613/”
; Directory in which the loadable extensions (modules) reside.
extension_dir = “/opt/module/php/lib/php/extensions/no-debug-non-zts-20060613/”
最后一步是验证安装是否成功。
1. 重启 Apache 服务器或 php-fpm 进程。
2. 运行命令 /opt/module/php/bin/php -m 检查输出列表中是否包含 laiwenhui 扩展。
进行功能测试验证。
在网站根目录下新建文件 test.php。
vim test.php
文件内容编写如下。
<?php echo test();
?> 执行该脚本后,预期输出结果为:This my first extention!
若上述步骤均顺利执行,即表示首个扩展开发成功。
以上为扩展 PHP 的基础操作指引,更多高级内容可参考相关文档: