PHP扩展开发与实践
C扩展原生开发
Zephir语言开发扩展
Hello World!示例
C 扩展原生开发
优点:性能,操作底层接口(内存),修改内核行为 缺点:对于不熟c语言,难上手,同时还需要阅读ZEND_API
参考文档:
实现过程:
下载php-src源码
编译工具
gcc c语言编译器
make c/c++自动构建工具
autoconf 检查系统环境与编译参数
进入php-src 目录结构
bulid
ext(php自带扩展)
ext_skel(创建扩展工程脚本)
....
main
netware
....
执行./ext_skel --extname=test 创建一个test扩展工程 juzhag@juzhag-virtual-machine:/mnt/hgfs/ubuntu/php/php-5.5.27/ext$ ./ext_skel --extname=test
Creating directory test
Creating basic files: config.m4 config.w32 .svnignore test.c php_test.h CREDITS EXPERIMENTAL tests/001.phpt test.php [done].
To use your new extension, you will have to execute the following steps:
1. $ cd ..
2. $ vi ext/test/config.m4
3. $ ./buildconf
4. $ ./configure --[with|enable]-test
5. $ make
6. $ ./sapi/cli/php -f ext/test/test.php
7. $ vi ext/test/test.c
8. $ make
Repeat steps 3-6 until you are satisfied with ext/test/config.m4 and
step 6 confirms that your module is compiled into PHP. Then, start writing
code and repeat the last two steps as often as necessary.
juzhag@juzhag-virtual-machine:/mnt/hgfs/ubuntu/php/php-5.5.27/ext$ cd test/
juzhag@juzhag-virtual-machine:/mnt/hgfs/ubuntu/php/php-5.5.27/ext/test$ ll
total 24
drwxrwxrwx 1 root root 4096 7月 19 13:39 ./
drwxrwxrwx 1 root root 8192 7月 19 13:39 ../
-rwxrwxrwx 1 root root 1986 7月 19 13:39 config.m4*
-rwxrwxrwx 1 root root 282 7月 19 13:39 config.w32*
-rwxrwxrwx 1 root root 4 7月 19 13:39 CREDITS*
-rwxrwxrwx 1 root root 0 7月 19 13:39 EXPERIMENTAL*
-rwxrwxrwx 1 root root 2812 7月 19 13:39 php_test.h*
-rwxrwxrwx 1 root root 16 7月 19 13:39 .svnignore*
-rwxrwxrwx 1 root root 5044 7月 19 13:39 test.c*
-rwxrwxrwx 1 root root 496 7月 19 13:39 test.php*
drwxrwxrwx 1 root root 0 7月 19 13:39 tests/
注意到config.m4,autoconf的配置文件,编写test扩展配置dnl 注释去除 PHP_ARG_WITH(test, for test support,
[ --with-test Include test support])
执行phpize命令,根据php的版本信息,生成configure文件
执行./configure shell脚本检查编译环境
产生Makefile编译的配置文件
make && make install
在php.ini添加 test.so
测试test目录下的test.php文件即可证明是否生效confirm_test_compiled函数
接下来进行hello world 示例编写
注意刚才test目录下有php_test.h头文件,test.c源文件
php_test.h 声明一个函数 PHP_FUNCTION(test_hello);
test.c 编写源码 PHP_FUNCTION(test_hello)
{
int len;
char *strg;
len = spprintf(&strg, 0, "Hello World");
RETURN_STRINGL(strg, len, 0);
}
test.c 编写源码,注册函数 const zend_function_entry test_functions[] = {
PHP_FE(test_hello, NULL)
}
重新make && make install
编写php脚本,执行 echo test_hello();
上述RETURN_STRINGL,PHP_FE...具体代码使用api,请参考zend API,在php源码根目录下的zend目录zend_API.h文件
Zephir语言开发扩展
优点:类似php语言书写,易上手,快速生成c扩展
缺点:还是得看文档
gcc >= 4.x/clang >= 3.x
re2c 0.13 or later
gnu make 3.81 or later
autoconf 2.31 or later
automake 1.14 or later
libpcre3
php development headers and tools
安装成功:
编写hello world 案例
zephir init utils 初始化工程,命名为utils
cd utils
vi utils/greeting.zep namespace Utils;
class Greeting
{
public static function say()
{
echo "hello world!";
}
}
zephir build
vi php.ini extension=utils.so
php test.php <?php
echo Utils\Greeting::say(), "\n";
Hello World就是这么简单易用,具体开发细节请查看手册
@date 2015/7/19 16:27:25