第一个php扩展

在阅读yaf源码的前提驱动下,了解了php扩展开发的基本步骤。基于php-src提供的ext_skel脚手架生成php扩展的基础代码,我的目的主要是先了解扩展开发的基本步骤,没有改其中的代码,以快速地过一遍php扩展开发重要的流程。这里有个前提是需要准备好指定版本的php-src源码并完成编译安装。

1. 使用ext_skel生成基础代码

进入 php-src/ext/目录,执行:

//我给我的第一个扩展名取名叫firstext
$ ./ext_skel --extname=firstext

返回:

Creating directory firstext
Creating basic files: config.m4 config.w32 .gitignore firstext.c php_firstext.h CREDITS EXPERIMENTAL tests/001.phpt firstext.php [done].

To use your new extension, you will have to execute the following steps:

1.  $ cd ..
2.  $ vi ext/firstext/config.m4
3.  $ ./buildconf
4.  $ ./configure --[with|enable]-firstext
5.  $ make
6.  $ ./sapi/cli/php -f ext/firstext/firstext.php
7.  $ vi ext/firstext/firstext.c
8.  $ make

Repeat steps 3-6 until you are satisfied with ext/firstext/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.

这时,我们看 ext 目录下多了 firstext 目录,里面的结构:

.
├── config.m4
├── config.w32
├── CREDITS
├── EXPERIMENTAL
├── firstext.c   //扩展通常要有一个 扩展名.c 的一个主文件
├── firstext.php
├── php_firstext.h //扩展通常要有一个php_扩展名.h的一个头文件
└── tests
    └── 001.phpt

2. 配置IDE

在修改扩展代码之前,我们用IDE 先打开项目,我用的是Clion,需要import project,而不是open一个文件夹,前者会自动生成MakeList,以便IDE自动提示。 自动生成后还要手动增加几条配置,如下

cmake_minimum_required(VERSION 3.10)
project(firstext C)

set(CMAKE_C_STANDARD 11)

include_directories(.)

add_executable(firstext
        firstext.c
        php_firstext.h)

#手动增加的配置
#定义php源码路径,这里根据自己的真实路径来更改
set(PHP_SOURCE /host/code/github/read-code/php-7.1.18/)
#引入php需要的扩展源码,这里也是根据自己需要的来更改
include_directories(${PHP_SOURCE}/main)
include_directories(${PHP_SOURCE}/Zend)
include_directories(${PHP_SOURCE}/sapi)
include_directories(${PHP_SOURCE}/pear)
include_directories(${PHP_SOURCE})

add_custom_target(makefile COMMAND sudo /host/tools/php7.1.18/bin/phpize && ./configure --with-php-config=/host/tools/php7.1.18/bin/php-config &&  make
        WORKING_DIRECTORY ${PROJECT_SOURCE_DIR})

3. 修改config.m4

这时候需要修改编译配置文件了。这个config.m4是用于配置扩展的支持选项、及依赖的库等。针对类unix系统提供的是config.m4,是基于autoconf语法编写的,还有一种是config.w32是为windows系统编译用的。

第一次我没改config.m4直接进入配置编译,然后就报modules不存在错了,于是我参考 https://blog.csdn.net/21aspnet/article/details/7345650 ,将 PHP_ARG_ENABLE 取消注释,后面就能跑的通了。

4. 配置编译

接下来就是跟安装php扩展一样的步骤了。 在扩展目录下执行:

$ /host/tools/php7.1.18/bin/phpize
Configuring for:
PHP Api Version:         20160303
Zend Module Api No:      20160303
Zend Extension Api No:   320160303

$  ./configure --with-php-config=/host/tools/php7.1.18/bin/php-config
......
$ make && make install
nstalling shared extensions:     /host/tools/php7.1.18/lib/php/extensions/no-debug-non-zts-20160303/

扩展编译安装完成,在php.ini中加入:

extension=firstext.so

执行命令:

/host/tools/php7.1.18/bin/php -m|grep firstext
firstext

显示有这个插件,就完成了。

猜你喜欢

转载自my.oschina.net/flyrobin/blog/1819314