PHP 的功能擴充可以走 PHP 5 內建的擴充骨架工具 ext_skel:先寫一份函式原型,讓工具產生目錄與 C 檔案骨架,填補你要的邏輯,再編譯成 .so,最後在 php.ini 裡載入。下面以一個只會說 "Hello" 的 tsing 擴充為例,把整個流程走一遍。
從官方下載頁 https://www.php.net/downloads.php#v5 取得 PHP 5 的原始碼包並解壓,擴充相關的工具都在 ext 目錄下。
先用編輯器建立一份原型檔 tsing.proto,一行寫完你要對外暴露的函式簽名:
$ cd php-5.2.5/ext $ gedit tsing.proto string say_hello(string str_name)
存檔後離開編輯器。這份檔案稍後會交給 ext_skel 解析。
$ ./ext_skel --extname=tsing --proto=tsing.proto $ cd tsing
ext_skel 顧名思義就是「產生骨架」:以 --extname 指定模組名稱,並在 ext 底下建立同名的目錄,裡頭已經備好 config.m4、tsing.c、php_tsing.h 等檔案。
打開 config.m4,把其中一組 dnl 註解標記拿掉,二選一:
PHP_ARG_WITH(tsing, for tsing support, Make sure that the comment is aligned: [ --with-tsing Include tsing support]) PHP_ARG_ENABLE(tsing, whether to enable test support, Make sure that the comment is aligned: [ --enable-tsing Enable test support])
兩者的差別在於是否需要第三方函式庫:--with-tsing 代表要連結外部的庫,--enable-tsing 則代表純粹是 PHP 自身的功能。本例不需要外部庫,用 enable 即可。
打開 tsing.c,你會發現原型檔裡的函式已經被自動註冊進函式表:
zend_function_entry tsing_functions[] = {
PHP_FE(confirm_tsing_compiled, NULL) /* For testing, remove later. */
PHP_FE(say_hello, NULL)
{NULL, NULL, NULL} /* Must be the last line in tsing_functions[] */
};
再往下約第 177 行,會看到對應的函式空殼:
PHP_FUNCTION(say_hello)
{
char *str_name = NULL;
int argc = ZEND_NUM_ARGS();
int str_name_len;
if (zend_parse_parameters(argc TSRMLS_CC, "s", &str_name, &str_name_len) == FAILURE)
return;
php_error(E_WARNING, "say_hello: not yet implemented");
}
把最後那行警告註解掉,換成真正的輸出:
// php_error(E_WARNING, "say_hello: not yet implemented");
php_printf("Hello, %s;", str_name);
順手確認 php_tsing.h 裡也已經有了對外宣告:
PHP_FUNCTION(say_hello);
# ./buildconf --force # ./configure --disable-all --with-tsing=shared --with-apxs2=/usr/sbin/apxs --prefix=/usr/lib/php/modules
--force 是為了避免你手上的 PHP 是 release 版本而跳過 rebuild;--disable-all 大幅減少預設要編的模組,編譯快很多;--with-tsing=shared 讓結果以 .so 動態模組的形式產出;--with-apxs2 的路徑要依你機器上 Apache 的安裝位置與版本而調整。
使用 PHP 安裝目錄下的 bin/phpize,在 tsing 目錄中直接產生 configure:
$ /usr/bin/phpize $ ./configure --with-php-config=/usr/bin/php-config --enable-tsing=shared --with-apxs2=/usr/sbin/apxs --prefix=/usr/lib/php/modules
# make # gedit /etc/php.d/tsing.ini # 加入 extension=tsing.so # make install # 或手動複製 # cp ./ext/tsing/.libs/tsing.so /usr/lib/php/ext/
完成後重啟 Apache,開一個 phpinfo() 頁面確認列表裡多出了 tsing 這一欄,就代表模組已被成功載入。
echo say_hello("Tsing");
輸出:
Hello,Tsing;
從原型檔到一個能被 PHP 呼叫的函式,中間其實只隔著「產生骨架 → 填邏輯 → 編譯成 shared → 在 ini 裡載入」這四步。之後若要加更多函式,只要擴充 tsing.proto 與 tsing_functions[],重跑一次流程即可。