PHP7新建擴展

一、你已經配置過PHP7的開發環境。

1.1 檢查centos安裝源

yum list installed | grep php

有則刪除舊的:php

 yum remove php*

1.2 添加新的安裝源

# CentOS 5.X
rpm -Uvh http://mirror.webtatic.com/yum/el5/latest.rpm
# CentOs 6.x
rpm -Uvh http://mirror.webtatic.com/yum/el6/latest.rpm
# CentOs 7.X
rpm -Uvh https://mirror.webtatic.com/yum/el7/epel-release.rpm
rpm -Uvh https://mirror.webtatic.com/yum/el7/webtatic-release.rpm

想要刪除上面的安裝包:web

rpm -qa | grep webstatic

1.3 安裝PHP開發環境

 yum install php70w.x86_64 php70w-cli.x86_64 php70w-common.x86_64 php70w-devel.x86_64

二、下載一份對應版本的PHP源代碼

cd php_src/ext/
./ext_skel --extname=hello

進入源代碼的ext目錄,並新建一個hello的插件;extname參數的值就是擴展名稱。執行ext_skel命令後,這樣在當前目錄下會生成一個與擴展名同樣的目錄。shell

三、修改config.m4配置文件

cd hello
vim config.m4

打開,config.m4文件後,你會發現如下內容vim

dnl If your extension references something external, use with:
   
 dnl PHP_ARG_WITH(say, for say support,
 dnl Make sure that the comment is aligned:
 dnl [  --with-say             Include say support])
 
 dnl Otherwise use enable:
 
 dnl PHP_ARG_ENABLE(say, whether to enable say support,
 dnl Make sure that the comment is aligned:
 dnl [  --enable-say           Enable say support])

其中,dnl 是註釋符號。centos

上面的代碼說,若是你所編寫的擴展若是依賴其它的擴展或者lib庫,須要去掉PHP_ARG_WITH相關代碼的註釋。php7

不然,去掉 PHP_ARG_ENABLE 相關代碼段的註釋。咱們編寫的擴展不須要依賴其餘的擴展和lib庫。所以,咱們去掉PHP_ARG_ENABLE前面的註釋。函數

去掉註釋後的代碼以下:php-fpm

dnl If your extension references something external, use with:
   
 dnl PHP_ARG_WITH(say, for say support,
 dnl Make sure that the comment is aligned:
 dnl [  --with-say             Include say support])
 
 dnl Otherwise use enable:
 
 PHP_ARG_ENABLE(say, whether to enable say support,
 Make sure that the comment is aligned:
 [  --enable-say           Enable say support])

四、修改代碼

修改 hello.c 文件,實現 hello() 函數;找到 PHP_FUNCTION(confirm_hello_compiled) 在上面添加如下內容:測試

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

PHP_FUNCTION 爲定義PHP內部函數括號裏面的爲函數名,而後再使用下面的修改將函數公開到插件外部。spa

找到 PHP_FE(confirm_hello_compiled 在上面增長以下代碼:

PHP_FE(hello, NULL)

即修改後效果:

const zend_function_entry hello_functions[] = {
     PHP_FE(hello, NULL)       /* For testing, remove later. */
     PHP_FE(confirm_hello_compiled,    NULL)       /* For testing, remove later. */
     PHP_FE_END  /* Must be the last line in say_functions[] */
 }; /* }}} */

其中上面的代碼中「confirm_hello_compiled」爲測試函數,可在實際項目中刪除

五、編譯

phpize
./configure
make
make test
# 會提醒輸入郵箱
make install
# 會提示編譯後輸入的目錄 目測:/lib64/php/modules/hello.so

六、添加配置

[hello]
extension = hello.so

七、測試效果

你可使用 「php -m」查看加載擴展,不過這裏請注意,若是php-cli命令和web php的配置文件不是同一個配置文件,則可能會出現差錯,推薦先經過phpinfo();查看web php配置文件,而後使用「php --ini」查看php-cli配置文件。

樓主web的php-fpm是編譯的,php-cli是經過yum安裝的,因此不一樣。

/etc/php.ini
/usr/local/php7/etc/php.ini
相關文章
相關標籤/搜索