為什么要用到php擴展?因為php擴展使用C語言編寫,而C語言是靜待編譯的,所以執行效率要高于php很多,這里我來實現一個完成一個簡單的Helloworld函數的例子。
生成框架
首先我們要生成擴展開發的框架,先下載php的源碼,在php的源碼/ext/目錄下有一個文件ext_skel,他是專門用來生成擴展開發必要文件的文件。
命令:
tongkundeMacBook-Pro:ext tongkun$ ./ext_skel --extname=Helloworld
Creating directory Helloworld
Creating basic files: config.m4 config.w32 .gitignore Helloworld.c php_Helloworld.h CREDITS EXPERIMENTAL tests/001.phpt Helloworld.php [done].
To use your new extension, you will have to execute the following steps:
1. $ cd ..
2. $ vi ext/Helloworld/config.m4
3. $ ./buildconf
4. $ ./configure --[with|enable]-Helloworld
5. $ make
6. $ ./sapi/cli/php -f ext/Helloworld/Helloworld.php
7. $ vi ext/Helloworld/Helloworld.c
8. $ make
Repeat steps 3-6 until you are satisfied with ext/Helloworld/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目錄下生成Helloworld目錄,目錄里有config.m4、haosoft_php_module.h和haosoft_php_module.c等幾個文件
配置文件
-
首先修改
config.m4
文件,刪除下面三項前面的dnl
注釋。##動態編譯選項,通過.so的方式鏈接,去掉dnl注釋 PHP_ARG_WITH(Helloworld, for Helloworld support, [ --with-Helloworld Include Helloworld support]) ##靜態編譯選項,通過enable來啟用,去掉dnl注釋 PHP_ARG_ENABLE(Helloworld, whether to enable Helloworld support, [ --enable-Helloworld Enable Helloworld support])
-
修改完成編譯一下,依次執行以下命令:
phpize ./configure --enable-Helloworld make make install
?
以上命令執行后,會在擴展目錄生成Helloworld.php的測試文件,測試文件已動態的方式加載擴展進行測試,執行:
#執行 php -d enable_dl=On Helloworld.php #輸出 Functions available in the test extension: confirm_Helloworld_compiled Congratulations! You have successfully modified ext/Helloworld/config.m4. Module Helloworld is now compiled into PHP.
通過設置enable_dl=On的方式開啟php動態加載,輸出如上內容說明擴展編譯成功
修改代碼,實現功能
通過vim打開Helloworld.c文件
-
找到
PHP_FUNCTION(confirm_Helloworld_compiled)
函數,修改為:PHP_FUNCTION(Helloworld) { php_printf("Hello World!\n"); RETURN_TRUE; }
-
修改函數定義處:
const zend_function_entry Helloworld_functions[] = { PHP_FE(Helloworld, NULL) /* For testing, remove later. */ PHP_FE_END /* Must be the last line in Helloworld_functions[] */ };
-
重新編譯,這里要帶上php-config 目錄
./configure --with-php-config=/usr/local/Cellar/php56/5.6.24/bin/php-config make make install
-
這時在module目錄下就會生成Helloworld.so 文件,拷貝到php的擴展目錄,可以參見php.ini 中的ext_dir 配置
cp modules/Helloworld.so /usr/local/etc/php/5.6/extensions/
重啟php-fpm,然后在php中直接調用
Helloworld
即可輸出Hellowold 說明測試完成
對于在php擴展中怎樣使用zval變量,C語言函數等在后續學習補充。
參考: