这两天一直在开发PHP扩展,写了一个微信的扩展应用,好多朋友一直在问,如何写扩展,这里我就介绍一下,也是因为这两天公司忙,博客没怎么更新,Docker 也没更新 抱歉了。
前提
- 一台 LINUX 主机( windows也可以,可以看我前边的文档 windows 开发 php 扩展 )
- 官网下载 php 源码 ( windows 复杂点,前边有文档,php5.5 以下记得是vc9)
- 要会C语言,查看一下ZEND API
开发
Linux 举例开发,将下载好的php解压到一个目录,譬如我的mac目录是 ~/php/phpcode
cd ~/php/phpcode/ext
./ext_skel --extname=hello  //这里我们假设开发一个 hello 的扩展
编写代码
php_hello.h,在PHP_FUNCTION(confirm_hello_compiled);后加一个函数
PHP_FUNCTION(hello);
编写代码
hello.c,PHP_FE(confirm_hello_compiled, NULL)后加一行
PHP_FE(hello,   NULL)
然后,你可以在
PHP_FUNCTION(confirm_widuu_compiled)后定义一个函数,代码如下
PHP_FUNCTION(hello){
    php_printf("hello word");
}
在修改
config.m4中的文件,去除这三行文件前边的dnl,如下效果
PHP_ARG_ENABLE(hello, whether to enable hello support,
Make sure that the comment is aligned:
[  --enable-hello           Enable hello support]) 
命令行,执行
path/phpize && ./configure && make
最后测试
cd modules && php -d extension=hello.so -r "hello();"
输出 hello word
可以这样
当然如果你比较熟悉的话,你可以跟我一样,直接建立一个文件夹手写,如下代码
hello.c
/**
 * @author widuu <admin@widuu.com>
 */
// 必须包含的 PHP 头文件 
#include "php.h"
/**
 * 模块介绍
 */
#define PHP_HELLO_EXTNAME "hello"
#define PHP_HELLO_VERSION "0.0.1"
/**
 * 定义 hello 方法必须包含的一个参数
 * function hello (string name)
 */
ZEND_BEGIN_ARG_INFO(hello_arginfo,0)
    ZEND_ARG_INFO(0,name)
ZEND_END_ARG_INFO()
/**
 * hello 函数
 */
static PHP_FUNCTION(hello){
    char *name;
    int  name_len;
    //参数大于1 报错
    if( ZEND_NUM_ARGS()>1 ){
        WRONG_PARAM_COUNT;
    }
    if(zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name, &name_len) == FAILURE){
        return;
    }
    RETURN_STRINGL(name,name_len,0);
}
/**
 * 函数 API 列表
 */
static zend_function_entry hello_functions[] = {
    PHP_FE(hello,   hello_arginfo)      /* hello 方法 */
    PHP_FE_END  /* Must be the last line in hello_functions[] */
};
/**
 * phpinfo 信息
 */
PHP_MINFO_FUNCTION(hello)
{
    php_info_print_table_start();
    php_info_print_table_header(2, "hello support", "enabled");
    php_info_print_table_row(2, "Version", PHP_HELLO_VERSION);
    php_info_print_table_end();
}
/**
 * 模块信息
 */
zend_module_entry hello_module_entry = {
#if ZEND_MODULE_API_NO >= 20010901
    STANDARD_MODULE_HEADER,
#endif
    PHP_HELLO_EXTNAME,
    hello_functions,
    NULL,
    NULL,
    NULL,       
    NULL,   
    PHP_MINFO(hello),
#if ZEND_MODULE_API_NO >= 20010901
    PHP_HELLO_VERSION,
#endif
    STANDARD_MODULE_PROPERTIES
};
ZEND_GET_MODULE(hello)
config.m4内容如下
PHP_ARG_ENABLE(hello, 
    whether to enable Hello extension, 
[ --enable-hello-php Enable Hello extension])
if test "$PHP_HELLO" != "no"; then
PHP_NEW_EXTENSION(hello, hello.c, $ext_shared)
fi
安装方法是一样的。
好今天就到这,然后后边我也会带大家用 zephir 重写微信模块。因为那个不需要 C 语言基础。更多问题,可以去社区 www.weiduyun.com 提问。
 
                 
                 
                
发表评论 取消回复