PHP扩展开发-1

开发环境信息

1、基本环境信息如下:

[root@localhost lib]# cat /etc/os-release
NAME="CentOS Linux"
VERSION="7 (Core)"
ID="centos"
ID_LIKE="rhel fedora"
VERSION_ID="7"
PRETTY_NAME="CentOS Linux 7 (Core)"
ANSI_COLOR="0;31"
CPE_NAME="cpe:/o:centos:centos:7"
HOME_URL="https://www.centos.org/"
BUG_REPORT_URL="https://bugs.centos.org/"

CENTOS_MANTISBT_PROJECT="CentOS-7"
CENTOS_MANTISBT_PROJECT_VERSION="7"
REDHAT_SUPPORT_PRODUCT="centos"
REDHAT_SUPPORT_PRODUCT_VERSION="7"

2、开发环境最好已经安装好了PHP,这样在编译、测试等环节就不会遇到不必要的麻烦了。
建议在Linux环境下开发PHP扩展,上边列出来的是我使用的开发环境信息。

PHP版本信息

[root@localhost lib]# php -v
PHP 7.0.17 (cli) (built: Mar 30 2017 07:50:59) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2017 Zend Technologies

Hello World扩展开发

(1)、cd进入PHP源码目录下的ext目录;
(2)、创建扩展程序骨架信息,执行下边命令就会在当前目录下创建好一个名为hello的扩展目录,该目录下即为这个扩展的骨架代码;

./ext_skel --extname=hello

(3)、修改hello目录下的config.m4文件,修改信息如下:

dnl If your extension references something external, use with:

dnl PHP_ARG_WITH(hello, for hello support,
dnl Make sure that the comment is aligned:
dnl [  --with-hello             Include hello support])

dnl Otherwise use enable:

dnl PHP_ARG_ENABLE(hello, whether to enable hello support,
dnl Make sure that the comment is aligned:
dnl [  --enable-hello           Enable hello support])

dnl是注释符号,这里把最后三行的注释去掉就行了。

(4)、修改hello目录下的hello.c文件,实现hello方法,修改内容如下:
找到PHP_FUNCTION(confirm_hello_compiled),在其上面增加如下代码:

PHP_FUNCTION(hello)
{
    zend_string *strg;
    strg = strpprintf(0, "hello word");
    RETURN_STR(strg);
}

找到PHP_FE(confirm_hello_compiled, NULL),在其上面增加如下代码:

PHP_FE(hello, NULL)

编译安装

在hello目录下执行如下命令:

phpize
./configure
make && make install

执行成功后,会在执行信息的最后看到下边这句话,这句话告知了生成的扩展的存放目录,cd进去可以看到编译好的扩展hello.so

Installing shared extensions:     /usr/local/lib/php/extensions/no-debug-non-zts-20151012/

然后去修改php.ini(这个文件通常是在/usr/local/lib目录下)文件,在扩展信息那边加上extension = hello.so,保存后执行php -m就可以看到hello这个扩展了

几个注意点如下
(1)、在执行phpize之前可以先执行whereis phpize确认下phpize的实际位置;
(2)、在执行phpize的时候可能会提示下边信息:

[root@localhost hello]# /usr/local/bin/phpize
Configuring for:
PHP Api Version:         20151012
Zend Module Api No:      20151012
Zend Extension Api No:   320151012
Cannot find autoconf. Please check your autoconf installation and the
$PHP_AUTOCONF environment variable. Then, rerun this script.

出现这个问题最简单的解决办法就是分别安装下m4和autoconf,安装命令如下:

yum install m4
yum install autoconf

测试扩展

直接在控制台输入php -r "echo hello();",看到输出 hello word 就表示成功啦_

posted @ 2017-06-24 21:49  chaojianok  阅读(712)  评论(0编辑  收藏  举报