Home | 簡體中文 | 繁體中文 | 雜文 | 打賞(Donations) | ITEYE 博客 | OSChina 博客 | Facebook | Linkedin | 知乎專欄 | Search | Email

第 20 章 PHP Extension 擴展開發

目錄

20.1. Extension Example 創建一個擴展
20.2. PHP_FUNCTION
20.3. PHP_INI
20.4. PHP_MINFO_FUNCTION
20.5. zval to string
20.6. 提交代碼到 Composer repository

創建一個擴展只需要下面幾個步驟

	
# cd php-5.4.14/ext/
# ./ext_skel --extname=netkiller
# cd netkiller
# /srv/php-5.4.8/bin/phpize
# ./configure --enable-netkiller --with-php-config=/srv/php-5.4.8/bin/php-config
# make
# make install
	
	

20.1. Extension Example 創建一個擴展

下面我們開始分部講解,首先創建一個擴展。

		
./ext_skel --extname=netkiller
Creating directory netkiller
Creating basic files: config.m4 config.w32 .cvsignore netkiller.c php_netkiller.h CREDITS EXPERIMENTAL tests/001.phpt netkiller.php [done].

To use your new extension, you will have to execute the following steps:

1.  $ cd ..
2.  $ vi ext/netkiller/config.m4
3.  $ ./buildconf
4.  $ ./configure --[with|enable]-netkiller
5.  $ make
6.  $ ./php -f ext/netkiller/netkiller.php
7.  $ vi ext/netkiller/netkiller.c
8.  $ make

Repeat steps 3-6 until you are satisfied with ext/netkiller/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.
		
		

編輯config.m4

		
# vim netkiller/config.m4
PHP_ARG_ENABLE(netkiller, whether to enable netkiller support,
Make sure that the comment is aligned:
[  --enable-netkiller           Enable netkiller support])
		
		

去掉上面三行前的dnl, dnl 表示註釋

		
# cat config.m4 | grep -v 'dnl'

PHP_ARG_ENABLE(netkiller, whether to enable netkiller support,
Make sure that the comment is aligned:
[  --enable-netkiller           Enable netkiller support])

if test "$PHP_netkiller" != "no"; then

  PHP_NEW_EXTENSION(netkiller, netkiller.c, $ext_shared)
fi
		
		

執行 phpize

		
# cd netkiller
# /srv/php-5.4.8/bin/phpize
Configuring for:
PHP Api Version:         20100412
Zend Module Api No:      20100525
Zend Extension Api No:   220100525

# ./configure --enable-netkiller --with-php-config=/srv/php-5.4.8/bin/php-config
# make
# make install

# ls modules/
netkiller.la  netkiller.so
		
		

創建 ini 檔案

		
cat >> /srv/php/etc/conf.d/netkiller.ini <<PHP
extension=netkiller.so
PHP
		
		

確認擴展看裝成功

		
# /srv/php/bin/php -f netkiller.php
Functions available in the test extension:
confirm_netkiller_compiled

Congratulations! You have successfully modified ext/netkiller/config.m4. Module netkiller is now compiled into PHP.

# /srv/php-5.4.8/bin/php -m | grep netkiller
netkiller
		
		

創建 php 測試程序

		
vim test.php

<?php
echo confirm_netkiller_compiled('netkiller');
phpinfo();
		
		

輸出結果

		
Congratulations! You have successfully modified ext/netkiller/config.m4. Module netkiller is now compiled into PHP.

netkiller
---------------------------
netkiller support	enabled