环境准备:
linux
php源码
1、先下载php源码
wget url
wget http://cn2.php.net/get/php-7.0.24.tar.gz/from/this/mirror
2、编译php,配置php环境
3、进入php源码路径
cd /etc/php/php-7.0.24/ext
4、使用ext_skel工具
./ext_skel --extname=hello
ext目录下多了一个hello目录,我们后续的工作都在这个目录下面,工具已经为我们自动生成了一些文件。
进入hello文件夹
cd /etc/php/php-7.0.24/ext/hello
vim打开config.m4文件
修改16-18行代码
dnf PHP_ARG_ENABLE(hello,whether to enable hello support,
dnf Make sure that the comment is aligned:
dnf [ --enable-hello Enable hello support])
修改后(去掉每行前边的dnf)
PHP_ARG_ENABLE(hello,whether to enable hello support,
Make sure that the comment is aligned:
[ --enable-hello Enable hello support])
php_hello.h头文件
类似于C语音的头文件,包含了一些自定义的结构和函数声明,在这个demo中暂时不需要改动
hello.c代码文件
真正的逻辑代码都在这个文件中,后面会详细介绍。
5、编写代码
vim hello.c
整个扩展的入口是zend_module_entry这个结构
/* {{{ hello_module_entry
*/
zend_module_entry hello_module_entry = {
STANDARD_MODULE_HEADER,
"hello",
hello_functions,
PHP_MINIT(hello),
PHP_MSHUTDOWN(hello),
PHP_RINIT(hello), /* Replace with NULL if there's nothing to do at request start */
PHP_RSHUTDOWN(hello), /* Replace with NULL if there's nothing to do at request end */
PHP_MINFO(hello),
PHP_HELLO_VERSION,
STANDARD_MODULE_PROPERTIES
};
/* }}} */
- STANDARD_MODULE_HEADER帮我们实现了前面6个属性
- “hello”是扩展的名字
- hello_functions是扩展包含的全部方法的集合
- 后面5个宏分别代表5个扩展特定方法
- PHP_HELLO_VERSION是扩展的版本号,定义在头文件中
- STANDARD_MODULE_PROPERTIES帮我们实现了剩下的属性
暂时都不需要修改,知道这是一个入口就行。顺着这个入口,我们继续看怎么给扩展添加方法,在hello_functions[]方法数组中已经有了一个示例方法confirm_hello_compiled,我们参考它写我们的方法hello_world
/* {{{ hello_functions[]
*
* Every user visible function must have an entry in hello_functions[].
*/
const zend_function_entry hello_functions[] = {
PHP_FE(confirm_hello_compiled, NULL) /* For testing, remove later. */
PHP_FE_END /* Must be the last line in hello_functions[] */
};
/* }}} */
修改后(添加了一行代码)
/* {{{ hello_functions[]
*
* Every user visible function must have an entry in hello_functions[].
*/
const zend_function_entry hello_functions[] = {
PHP_FE(confirm_hello_compiled, NULL) /* For testing, remove later. */
PHP_FE(hello_world, NULL) /* For testing, remove later. */
PHP_FE_END /* Must be the last line in hello_functions[] */
};
/* }}} */
接着往上翻找到
PHP_FUNCTION(confirm_hello_compiled)方法下边添加代码
PHP_FUNCTION(hello_world)
{
php_printf("Hello World!\n");
RETURN_TRUE;
}
6、编译安装
phpize
./configure
make
make install
之后会提示hello.so文件位置,或者自己指定生成位置也可以
复制扩展文件到php加载的扩展文件夹下
在php.ini中添加上扩展的配置
extension = hello.so
我这里是php-fpm。重启服务
php -m
应该可以看到hello的扩展名称
[PHP Modules]
...
curl
hello
...
[Zend Modules]
7、测试
写一个test.php方法,执行脚本就可以看到”Hello World!”
<?php
hello_world();