首頁  >  文章  >  後端開發  >  一步步入門編寫PHP擴展

一步步入門編寫PHP擴展

WBOY
WBOY原創
2016-07-25 09:12:32939瀏覽

1、寫在最前

隨著網路快速發展,lamp架構的流行,php支援的擴展也越來越多,這樣直接促進了php的發展。

但php也有腳本語言不可避免的問題,效能比例如C等編譯型語言相差甚多,所以在考慮效能問題的時候最好還是透過php擴充來解決。

那麼,怎麼做一個php擴充呢。下面從一個例子開始(本文章需要C基礎)。

2、解決一個問題

在一個系統中,如果常常要求一個陣列的平方和,我們可以這麼寫。

  1. function array_square_sum($data){
  2. $sum = 0;
  3. foreach($data as $value){
  4. $sum += $value * $value;
  5. }
  6. return $sum;
  7. }
複製程式碼

實際執行的時候,php zend引擎會把這段話翻譯成C語言,每次都需要進行記憶體分配。所以效能比較差。進而,基於效能上的考慮,我們可以寫一個擴充來做這個事情。

3、寫擴充

建立一個擴展,至少需要2個檔案。一個是Configulator文件,它會告訴編譯器編譯這個擴充至少需要哪些依賴函式庫;第二個是實際執行的文件。

3.1 生成框架

聽起來很複雜,實際上有一個工具可以幫我們搞定一個擴充的框架。在php原始碼裡面有個工具ext_skel,他可以幫我們產生擴充框架。

  1. liujun@ubuntu:~/test/php-5.5.8/ext$ ls ext_skel
  2. ext_skel
複製程式碼

現在我們利用它來產生擴充 array_square_sum。 ($表示提示符號指令)

  1. $ ./ext_skel --extname=array_square_sum
  2. Creating directory array_square_sum
  3. Creating bas . .svnignore array_square_sum.c php_array_square_sum.h CREDITS EXPERIMENTAL tests/001.phpt array_square_sum.php [done].
  4. 2. $ vi ext/array_square_sum/config.m4
  5. 3. $ ./buildconf
  6. 4. $ ./configure --[with|enable]-array_square_sum
  7. 5 . $ make
  8. 6. $ ./php -f ext/array_square_sum/array_square_sum.php
  9. 7. $ vi ext/array_square_sum/array_square_sum.c
  10. 8. $. $. 3-6 until you are satisfied with ext/array_square_sum/config.m4 and
  11. step 6 confirms that your module is compiled into PHP. Then, start writing
  12. code and meeat the last s stesm. 🎜>
  13. 複製程式碼
  14. 執行指令之後,終端告訴我們怎麼去生產新的擴充。檢視一下檔案內容,會發現多了幾個比較重要的檔案config.m4, php_array_square_sum.h,array_square_sum.c,下面會一一敘述。
liujun@ubuntu:~/test/php-5.5.8/ext$ ll array_square_sum/

total 44

drwxr-xjunlix 3 jun 4096 Jan 29 15:40 ./
drwxr-xr-x 80 liujun liujun 4096 Jan 29 15:40 ../
-rw-r--r-- 1 liujun liu0 554: Jan0 1 .c
    -rw-r--r-- 1 liujun liujun 532 Jan 29 15:40 array_square_sum.php
  1. -rw-r--r-- 1 liujun liujun 2354 Jan 29 15:40 config.
  2. -rw-r--r-- 1 liujun liujun 366 Jan 29 15:40 config.w32
  3. -rw-r--r-- 1 liujun liujun 16 Jan 29 15:40 CREDITS
  4. rw-r--r-- 1 liujun liujun 0 Jan 29 15:40 EXPERIMENTAL
  5. -rw-r--r-- 1 liujun liujun 3112 Jan 29 15:40 php_array_square_sum.hdrwxr-xr-x 2 liujun liujun 4096 Jan 29 15:40 tests/
  6. >
  7. 3.2 設定檔config.m4
dnl PHP_ARG_WITH(array_square_sum, for array_square_sum support,dnl squa --with-array_square_sum Include array_square_sum support])

複製程式碼

    去掉dnl
PHP_ARG_WITH(array_square_sum, for array_square_sum support,Make sure that thearra:com==,

複製程式碼

這是./configure時能夠呼叫enable-sample選項的最低要求.PHP_ARG_ENABLE的第二個參數將在./configure處理過程中到達這個擴充的設定檔時顯示. 第三個參數將在終端用戶執行./configure --help時顯示為幫助資訊

3.3 頭檔

修改php_array_square_sum.h,把confirm_array_square_sum_compiled改成confirm_array_square_sum,這個為我們以後實際呼叫的函式名字,當然你也可以直接加入函式碼_,

  1. PHP_FUNCTION(confirm_array_square_sum_compiled);
複製程式碼

複製程式碼
PHP_FUNCTION(array_square_sum);
複製程式碼

3.3 原始碼

修改 array_square_sum.c,把confirm_array_square_sum_compiled改成confirm_array_square_sum,這個是註冊這個擴充的函數,如果在3.2直接加入了confirm_array_square_sum,在這一步也直接加入了confirm_array_square_sum,在這一步驟也直接加入了這一步也可以。

const zend_function_entry array_square_sum_functions[] = {
    PHP_FE(confirm_array_square_sum_compiled, Ntest) /mild the last line in array_square_sum_functions[] */
  1. };
  2. 複製程式碼
改成

  1. const zend_function_entry array_square_sum_functions[] = {
  2. PHP_FE(array_square_sum, NULL) /* For testing, remove later. */
  3. PHP_FE_END /* Must bey last me_an 3m >
複製程式碼

然後最關鍵的步驟,重寫confirm_array_square_sum,這個時候只要把confirm_array_square_sum_compiled重寫成confirm_array_square_sum(3.1沒有刪除confirm_array_square_sum_compilm_sum(3.1中沒有刪除了confirm_array_square_sum_compilm_sumre_sum_compilm_conf_s。

PHP_FUNCTION(confirm_array_square_sum_compiled)
複製程式碼
複製程式碼

複製程式碼
  1. 複製程式碼
  2. 複製碼
  3. 重寫為
  4. PHP_FUNCTION(array_square_sum)
  5. {
  6. zval* array_data; char* key;
  7. uint index;
  8. zval **pdata;
  9. double sum = 0;
  10. if (zend_parse_parameters(ZEND_NUM_ARGS(> if (zend_parse_parameters(ZEND_NUM_ARGS() TSRM_CCGS() TS_D.M. = FAILURE) {
  11. return;
  12. }
  13. ht_data = Z_ARRVAL_P(array_data);
  14. zend_hash_internal_pointer_reset(ht_data);
  15. zend_hash_internal_pointer_reset(ht_data);
  16. , &key , &index, 0)) ) {
  17. ret = zend_hash_get_current_data(ht_data, &pdata);
  18. if( Z_TYPE_P(*pdata) == IS_LONG){
  19. sum += Z_LVAL_Pf Z_LVAL_P(*pdata);
}else {
RETURN_FALSE; } zend_hash_move_forward(ht_data);
}

zend_hash_internal_pointer_end(Z_ARRVAL_P(array_data));

RETVAL_DOUBLE(sum );

}複製程式碼

    php是一種弱型語言,他的資料都存在結構體zval裡面(
  1. 具體請看更專業資料,如"php擴充開發.pdf
  2. "
  3. )。
  4. typedef union _zval {
  5. long lval;
double dval;
struct { } str; HashTable *ht; zend_object_value obj;
} zval;

複製程式碼

    複製程式碼
為了得到函數傳遞的參數,可以使用zend_parse_parameters()API函數。以下是函數的原型:
zend_parse_parameters(int num_args TSRMLS_DC, char *type_spec, …);複製程式碼 🎜>

zend_parse_parameters()函數的前幾個參數我們直接用內核裡宏來產生便可以了,形式為:ZEND_NUM_ARGS() TSRMLS_CC,注意兩者之間有個空格,但是沒有逗號。從名字可以看出,ZEND_NUM_ARGS()代表這參數的數量。後面緊跟著是常見的參數型別(和C語言的printf類似),後面就是常見的參數列表。
下表列出了常見的參數類型。

参数类型 对象C类型 说明
l long 整数
b bool 布尔
s char* 字符串
d double 浮点数
a array(zval*) 数组
z zval* 不确定性zval


另外數組是一個大型的hashtable來實現的,所以zend_hash_get_current_key可以遍歷數組,使用宏Z_LVAL_P(zval*)來獲得實際的值。最終可以將結果放入到sum裡面。 RETVAL_DOUBLE(value)也是一個宏,回傳結果為double,值則為value,具體可以參考" php擴充開發.pdf".

最後完成了這個主函數的開發。

3.4 產生configure檔

然後執行 ~/php/bin/phpize

  1. /home/liujun/php/bin/phpize
複製程式碼

複製程式碼
Configuring for:
PHP Api Version: 20121113Zend Module Api No: 20121212Zend Extension Api No: 2201212120121>


可以發現array_square_sum出現執行腳本configure。

3.5 編譯

編譯的時候最好帶php-config PATH,因為系統預設的php-config-path可能不是你目前使用的php路徑。
liujun@ubuntu:~/test/php-5.5.8/ext/array_square_sum$ ./configure --with-php-config=/home/liujun/php /bin/php-config
複製程式碼

編譯如果成功,終端機會有以下提示:
  1. creating libtool
  2. appending configuration tag "CXX" to libtool
  3. configure: creating ./config.status
  4. config.status: creating config.h
config.status: config.h is change >
複製程式碼

看array_square_sum目錄的module目錄,會發現裡面產生array_square_sum.so,這就是我們需要的擴充功能。

  1. liujun@ubuntu:~/test/php-5.5.8/ext/array_square_sum$ ls modules/
  2. array_square_sum.la array_s modules/
array_square_sum.la array_squaremm> >
複製程式碼

4、使用擴充

4.1、設定擴充

修改php的設定php.ini,加入一下設定內容。

    [array_square_sum]
  1. extension=array_square_sum.so
複製程式碼

4.2、加入module

php的擴充一般在 $PHP_PATH/lib/php/extensions/no-debug-non-zts-yyyymmdd,如果找不到,請自行百度or Google. 裡面有很多.so檔。

把3.5生產的array_sum_square.so拷貝進去即可。

如果使用fastcgi模式,需要重啟php,這樣我們php就應該有擴充array_square_sum,具體可以透過查看phpinfo(不會請自行百度orGoogle).

4.2、寫程式

既然說編寫擴充功能可以提高運行效率,因此在這裡,我們透過使用擴充和直接使用php程式碼來進行對比,測試效能。多次實驗可以減少誤差,所以進行2000次對100000個數字求平方和。程式碼如下:

    $data = array();
  1. $max_index = 100000;
  2. $test_time = 2000time = 100000;
  3. $test_time = 2000>; for($i=0; $i $data[] = $i;
  4. }
  5. $php_test_time_start = time();
  6. php_test( $test_time, $data);
  7. $php_test_time_stop = time();
  8. echo "php test ext time is ". ($php_test_time_stop - $php_test_time_start). "n";
  9. c_test($test_time, $data);
  10. $c_test_time_stop = time();
  11. echo "php test time is ". ($c_test_time_stop - $c_test_time_start). "n"; 🎜>
  12. function php_test($test_time, $test_data){
  13. for($i=0; $i $sum = 0;
  14. foreach($test_data as $data){
  15. $sum += $data * $data;
  16. }
  17. }
  18. }
  19. function c_test($test_time, $test_data){
  20. for ($i=0; $i $sum = array_square_sum($test_data);
  21. }
  22. }
  23. 複製代碼
測試結果如下:

liujun@ubuntu:~/php$ ~/php/bin/php test.php
php test ext time is 30
    php test time is 2
  1. 複製程式碼

可以看到擴充要比直接使用php快15倍。隨著業務邏輯變得更加複雜,這個差異化會越大。

那麼直接用c語言來做這個事情呢。下面也給一個程式碼測試下(測試條件完全一致):

  1. #include
  2. #include
  3. #include
  4. #define TEST_TIME 2000
  5. #define MAX_INDEX 100000
  6. int main()
  7. {
  8. 🎜> double sum = 0;
  9. for(int i=0; i data[i] = i;
  10. }
  11. struct timeval start ;
  12. struct timeval end;
  13. gettimeofday(&start,NULL);
  14. for(int i=0; i for(int j=0 ; j sum += data[j] * data[j];
  15. }
  16. }
  17. gettimeofday(&end,NULL);
  18. double timeofday(&end,NULL);
  19. double time =(end.tv_sec-start.tv_sec) + (end.tv_usec-start.tv_usec) * 1.0 /1000000;
  20. printf("total time is %lfn", time );
  21. printf("sum time is %lfn", sum);
  22. return 0;
}
複製程式碼

執行查看效果,可以看出直接使用C的時間只有0.261746,是使用C擴充的13.09%,是直接使用php的0.87%。當然如果牽涉到IO等複雜操作,C/C++會比php快上萬倍(測試過)。

  1. liujun@ubuntu:~/php$ g++ test.cpp -O2 -o test
  2. liu php$ ./test
  3. total time is 0.261746
sum time is 36207007178615872.000000
複製程式碼

因此,在實際對效能要求非常高的服務,如索引、分詞等,可以使用C做一套底層服務,php去進行封裝呼叫。

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn