不要再天天寫表單了,淘寶大牛教你零基礎(chǔ)寫PHP擴展
很多PHPer天天寫表單,不知如何提升。如果你已經(jīng)熟悉了數(shù)據(jù)集和服務(wù)器端的優(yōu)化,不妨試試通過PHP擴展向系統(tǒng)層進軍。當原有的PHP代碼實現(xiàn)出現(xiàn)性能瓶頸,可以考慮通過PHP擴展實現(xiàn);純PHP代碼無法實現(xiàn)的功能,可以考慮通過PHP擴展調(diào)用其他相關(guān)庫實現(xiàn)。既能提升業(yè)務(wù)能力,又能幫助大家逐漸通過擴展了解PHP 源代碼層的運作機制。
擴展入門較難,這里特別推薦淘寶大牛信海龍老師的入門課程,手把手教會你只要一塊錢。
我們精選出文集中的第二章內(nèi)容,以供免費試讀。
(如果你不喜歡付費課程,也可以通過PHP手冊第二部分進行學習:http://php.net/manual/zh/internals2.structure.php)
從hello world開始(試讀)
以下內(nèi)容以PHP7作為基礎(chǔ),講解如何從零開始創(chuàng)建一個PHP擴展。示例中,我們將實現(xiàn)如下功能:
- <?php
- function say() {
- return "hello word";
- }
- echo say();
- ?>
輸出內(nèi)容:
- $ php ./test.php
- $ hello word
在擴展中實現(xiàn)一個say方法,調(diào)用say方法后,輸出 hello word。
***步:生成代碼
PHP為我們提供了生成基本代碼的工具 ext_skel。這個工具在PHP源代碼的./ext目錄下。
- $ cd php_src/ext/
- $ ./ext_skel --extname=say
extname參數(shù)的值就是擴展名稱。執(zhí)行ext_skel命令后,這樣在當前目錄下會生成一個與擴展名一樣的目錄。
第二步:修改config.m4配置文件
config.m4的作用就是配合phpize工具生成configure文件。configure文件是用于環(huán)境檢測的。檢測擴展編譯運行所需的環(huán)境是否滿足?,F(xiàn)在我們開始修改config.m4文件。
- $ cd ./say
- $ vim ./config.m4
打開,config.m4文件后,你會發(fā)現(xiàn)這樣一段文字。
- 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 是注釋符號。上面的代碼說,如果你所編寫的擴展如果依賴其它的擴展或者lib庫,需要去掉PHP_ARG_WITH相關(guān)代碼的注釋。否則,去掉 PHP_ARG_ENABLE 相關(guān)代碼段的注釋。我們編寫的擴展不需要依賴其他的擴展和lib庫。
因此,我們?nèi)サ鬚HP_ARG_ENABLE前面的注釋。去掉注釋后的代碼如下:
- 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])
第三步:代碼實現(xiàn)
修改say.c文件。實現(xiàn)say方法。 找到PHP_FUNCTION(confirm_say_compiled),在其上面增加如下代碼:
- PHP_FUNCTION(say)
- {
- zend_string *strg; strg = strpprintf(0, "hello word");
- RETURN_STR(strg);
- }
找到 PHP_FE(confirm_say_compiled, 在上面增加如下代碼:
- PHP_FE(say, NULL)
修改后的代碼如下:
- const zend_function_entry say_functions[] = {
- PHP_FE(say, NULL) /* For testing, remove later. */
- PHP_FE(confirm_say_compiled, NULL) /* For testing, remove later. */
- PHP_FE_END /* Must be the last line in say_functions[] */
- };
- /* }}} */
第四步:編譯安裝
編譯擴展的步驟如下:
- $ phpize
- $ ./configure
- $ make && make install
修改php.ini文件,增加如下代碼:
- [say]
- extension = say.so
然后執(zhí)行,php -m 命令。在輸出的內(nèi)容中,你會看到say字樣。
第五步:調(diào)用測試
自己寫一個腳本,調(diào)用say方法??摧敵龅膬?nèi)容是否符合預期。
- <?php
- echo say();
- ?>
輸出內(nèi)容:
- $ php ./test.php
- $ hello word
想深入學習PHP擴展的小伙伴,歡迎加入信海龍老師的特價付費圈子:零基礎(chǔ)學習PHP擴展開發(fā)