PHP開發入門2>PHP擴充開發入門2 HELLO WORLD

來源:互聯網
上載者:User
開發PHP擴充是一件很COOL的事情。不過難度自然要比開發PHP程式要複雜很多。畢竟是C語言。

我打一開始學習編程就是用的最笨的辦法。由於學習的不是電腦專業,所以學編程甚是頭大。和大多數哥哥姐姐弟弟妹妹一樣,我也是買了一本譚浩強的C語言,當然這個一方面是大家推薦,另外一方面譚老師的書在編程的書架上面放在了最醒目的位置,其他版本的在我們這個小地方也太難買到。

學習編程,開始就是抄代碼刪代碼,我覺得學這個開發擴充,開始不明白無所謂,先把編寫的過程結構給弄清楚,這個應該比較簡單,就是在什麼位置,寫什麼代碼,哪些可以修改,哪些不可以修改。熟悉過程了之後在去弄明白這段代碼是什麼意思,而且在刪除代碼的過程也就明白這段代碼所起的作用。

今天寫個‘hello world’,和所有的程式設計語言開始一樣。如何寫出來一個返回“hello world”的函數。

首先,在終端中找到PHP源碼的目錄,然後在ext目錄裡,輸入如下內容,其中"helloworld"為今天的函數名稱

./ext_skel  --extname=helloworld

接下來一起來見證奇蹟的誕生,ext目錄下有了helloworld目錄。這個是沒有任何功能的擴充,下面我們為其添加功能。

開啟php_helloworld.h檔案,在其中添加如下代碼

PHP_FUNCTION(hellworld);

添加後的檔案如下

/*  +----------------------------------------------------------------------+  | PHP Version 5                                                        |  +----------------------------------------------------------------------+  | Copyright (c) 1997-2015 The PHP Group                                |  +----------------------------------------------------------------------+  | This source file is subject to version 3.01 of the PHP license,      |  | that is bundled with this package in the file LICENSE, and is        |  | available through the world-wide-web at the following url:           |  | http://www.php.net/license/3_01.txt                                  |  | If you did not receive a copy of the PHP license and are unable to   |  | obtain it through the world-wide-web, please send a note to          |  | license@php.net so we can mail you a copy immediately.               |  +----------------------------------------------------------------------+  | Author:                                                              |  +----------------------------------------------------------------------+*//* $Id$ */#ifndef PHP_HELLOWORLD_H#define PHP_HELLOWORLD_Hextern zend_module_entry helloworld_module_entry;#define phpext_helloworld_ptr &helloworld_module_entry#define PHP_HELLOWORLD_VERSION "0.1.0" /* Replace with version number for your extension */#ifdef PHP_WIN32#define PHP_HELLOWORLD_API __declspec(dllexport)#elif defined(__GNUC__) && __GNUC__ >= 4#define PHP_HELLOWORLD_API __attribute__ ((visibility("default")))#else#define PHP_HELLOWORLD_API#endif#ifdef ZTS#include "TSRM.h"#endifPHP_MINIT_FUNCTION(helloworld);PHP_MSHUTDOWN_FUNCTION(helloworld);PHP_RINIT_FUNCTION(helloworld);PHP_RSHUTDOWN_FUNCTION(helloworld);PHP_MINFO_FUNCTION(helloworld);PHP_FUNCTION(confirm_helloworld_compiled);/* For testing, remove later. *///-----------------------------------------------------------start---------------------------------------------//這裡是我新增內容的開始PHP_FUNCTION(hellworld);//這裡結束//-----------------------------------------------------end------------------------------------------------/*   Declare any global variables you may need between the BEGINand END macros here:     ZEND_BEGIN_MODULE_GLOBALS(helloworld)long  global_value;char *global_string;ZEND_END_MODULE_GLOBALS(helloworld)*//* In every utility function you add that needs to use variables    in php_helloworld_globals, call TSRMLS_FETCH(); after declaring other    variables used by that function, or better yet, pass in TSRMLS_CC   after the last function argument and declare your utility function   with TSRMLS_DC after the last declared argument.  Always refer to   the globals in your function as HELLOWORLD_G(variable).  You are    encouraged to rename these macros something shorter, see   examples in any other php module directory.*/#ifdef ZTS#define HELLOWORLD_G(v) TSRMG(helloworld_globals_id, zend_helloworld_globals *, v)#else#define HELLOWORLD_G(v) (helloworld_globals.v)#endif#endif/* PHP_HELLOWORLD_H *//* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */

下面開啟helloworld.c,修改後如下

/*  +----------------------------------------------------------------------+  | PHP Version 5                                                        |  +----------------------------------------------------------------------+  | Copyright (c) 1997-2015 The PHP Group                                |  +----------------------------------------------------------------------+  | This source file is subject to version 3.01 of the PHP license,      |  | that is bundled with this package in the file LICENSE, and is        |  | available through the world-wide-web at the following url:           |  | http://www.php.net/license/3_01.txt                                  |  | If you did not receive a copy of the PHP license and are unable to   |  | obtain it through the world-wide-web, please send a note to          |  | license@php.net so we can mail you a copy immediately.               |  +----------------------------------------------------------------------+  | Author:                                                              |  +----------------------------------------------------------------------+*//* $Id$ */#ifdef HAVE_CONFIG_H#include "config.h"#endif#include "php.h"#include "php_ini.h"#include "ext/standard/info.h"#include "php_helloworld.h"/* If you declare any globals in php_helloworld.h uncomment this:ZEND_DECLARE_MODULE_GLOBALS(helloworld)*//* True global resources - no need for thread safety here */static int le_helloworld;/* {{{ helloworld_functions[] * * Every user visible function must have an entry in helloworld_functions[]. */const zend_function_entry helloworld_functions[] = {PHP_FE(confirm_helloworld_compiled,NULL)/* For testing, remove later. */PHP_FE(helloworld,NULL)         /* 在這裡添加代碼 ,和上個檔案中的函數名要一致*/PHP_FE_END/* Must be the last line in helloworld_functions[] */};/* }}} *//* {{{ helloworld_module_entry */zend_module_entry helloworld_module_entry = {#if ZEND_MODULE_API_NO >= 20010901STANDARD_MODULE_HEADER,#endif"helloworld",helloworld_functions,PHP_MINIT(helloworld),PHP_MSHUTDOWN(helloworld),PHP_RINIT(helloworld),/* Replace with NULL if there's nothing to do at request start */PHP_RSHUTDOWN(helloworld),/* Replace with NULL if there's nothing to do at request end */PHP_MINFO(helloworld),#if ZEND_MODULE_API_NO >= 20010901PHP_HELLOWORLD_VERSION,#endifSTANDARD_MODULE_PROPERTIES};/* }}} */#ifdef COMPILE_DL_HELLOWORLDZEND_GET_MODULE(helloworld)#endif/* {{{ PHP_INI *//* Remove comments and fill if you need to have entries in php.iniPHP_INI_BEGIN()    STD_PHP_INI_ENTRY("helloworld.global_value",      "42", PHP_INI_ALL, OnUpdateLong, global_value, zend_helloworld_globals, helloworld_globals)    STD_PHP_INI_ENTRY("helloworld.global_string", "foobar", PHP_INI_ALL, OnUpdateString, global_string, zend_helloworld_globals, helloworld_globals)PHP_INI_END()*//* }}} *//* {{{ php_helloworld_init_globals *//* Uncomment this function if you have INI entriesstatic void php_helloworld_init_globals(zend_helloworld_globals *helloworld_globals){helloworld_globals->global_value = 0;helloworld_globals->global_string = NULL;}*//* }}} *//* {{{ PHP_MINIT_FUNCTION */PHP_MINIT_FUNCTION(helloworld){/* If you have INI entries, uncomment these lines REGISTER_INI_ENTRIES();*/return SUCCESS;}/* }}} *//* {{{ PHP_MSHUTDOWN_FUNCTION */PHP_MSHUTDOWN_FUNCTION(helloworld){/* uncomment this line if you have INI entriesUNREGISTER_INI_ENTRIES();*/return SUCCESS;}/* }}} *//* Remove if there's nothing to do at request start *//* {{{ PHP_RINIT_FUNCTION */PHP_RINIT_FUNCTION(helloworld){return SUCCESS;}/* }}} *//* Remove if there's nothing to do at request end *//* {{{ PHP_RSHUTDOWN_FUNCTION */PHP_RSHUTDOWN_FUNCTION(helloworld){return SUCCESS;}/* }}} *//* {{{ PHP_MINFO_FUNCTION */PHP_MINFO_FUNCTION(helloworld){php_info_print_table_start();php_info_print_table_header(2, "helloworld support", "enabled");php_info_print_table_end();/* Remove comments if you have entries in php.iniDISPLAY_INI_ENTRIES();*/}/* }}} *//* Remove the following function when you have successfully modified config.m4   so that your module can be compiled into PHP, it exists only for testing   purposes. *//* Every user-visible function in PHP should document itself in the source *//* {{{ proto string confirm_helloworld_compiled(string arg)   Return a string to confirm that the module is compiled in */PHP_FUNCTION(confirm_helloworld_compiled){char *arg = NULL;int arg_len, len;char *strg;if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &arg, &arg_len) == FAILURE) {return;}len = spprintf(&strg, 0, "Congratulations! You have successfully modified ext/%.78s/config.m4. Module %.78s is now compiled into PHP.", "helloworld", arg);RETURN_STRINGL(strg, len, 0);}/* }}} *//* The previous line is meant for vim and emacs, so it can correctly fold and    unfold functions in source code. See the corresponding marks just before    function definition, where the functions purpose is also documented. Please    follow this convention for the convenience of others editing your code.*//* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */        /*  這裡是功能 這個函數不接收參數,只有傳回值。 */ PHP_FUNCTION(helloworld){        int  len;char *strg;len = spprintf(&strg, 0, "%.78s", "helloworld");RETURN_STRINGL(strg, len, 0);}

在編譯之前還需要修改一個檔案,就是config.m4,將10、11、12三行最前面的dnl刪除掉。這裡刪除這幾個注釋,是編譯的時候讓編譯這個擴充,不然就忽略了。

dnl $Id$dnl config.m4 for extension helloworlddnl Comments in this file start with the string 'dnl'.dnl Remove where necessary. This file will not workdnl without editing.dnl If your extension references something external, use with:PHP_ARG_WITH(helloworld, for helloworld support,Make sure that the comment is aligned:[  --with-helloworld             Include helloworld support])dnl Otherwise use enable:dnl PHP_ARG_ENABLE(helloworld, whether to enable helloworld support,dnl Make sure that the comment is aligned:dnl [  --enable-helloworld           Enable helloworld support])if test "$PHP_HELLOWORLD" != "no"; then  dnl Write more examples of tests here...  dnl # --with-helloworld -> check with-path  dnl SEARCH_PATH="/usr/local /usr"     # you might want to change this  dnl SEARCH_FOR="/include/helloworld.h"  # you most likely want to change this  dnl if test -r $PHP_HELLOWORLD/$SEARCH_FOR; then # path given as parameter  dnl   HELLOWORLD_DIR=$PHP_HELLOWORLD  dnl else # search default path list  dnl   AC_MSG_CHECKING([for helloworld files in default path])  dnl   for i in $SEARCH_PATH ; do  dnl     if test -r $i/$SEARCH_FOR; then  dnl       HELLOWORLD_DIR=$i  dnl       AC_MSG_RESULT(found in $i)  dnl     fi  dnl   done  dnl fi  dnl  dnl if test -z "$HELLOWORLD_DIR"; then  dnl   AC_MSG_RESULT([not found])  dnl   AC_MSG_ERROR([Please reinstall the helloworld distribution])  dnl fi  dnl # --with-helloworld -> add include path  dnl PHP_ADD_INCLUDE($HELLOWORLD_DIR/include)  dnl # --with-helloworld -> check for lib and symbol presence  dnl LIBNAME=helloworld # you may want to change this  dnl LIBSYMBOL=helloworld # you most likely want to change this   dnl PHP_CHECK_LIBRARY($LIBNAME,$LIBSYMBOL,  dnl [  dnl   PHP_ADD_LIBRARY_WITH_PATH($LIBNAME, $HELLOWORLD_DIR/$PHP_LIBDIR, HELLOWORLD_SHARED_LIBADD)  dnl   AC_DEFINE(HAVE_HELLOWORLDLIB,1,[ ])  dnl ],[  dnl   AC_MSG_ERROR([wrong helloworld lib version or lib not found])  dnl ],[  dnl   -L$HELLOWORLD_DIR/$PHP_LIBDIR -lm  dnl ])  dnl  dnl PHP_SUBST(HELLOWORLD_SHARED_LIBADD)  PHP_NEW_EXTENSION(helloworld, helloworld.c, $ext_shared)fi

到這裡就大功告成了。這裡開發工具已經做完了,剩下就是編譯了。在該擴充目錄下,依次執行如下命令

phpize
./configure --withphp-config=php-config
make
sudo make install

安裝之後,需要在PHP.INI檔案當中將擴充啟用,在該檔案最後一行添加

extension=helloworld.so

接下來一起見證奇蹟的誕生

   

這就是第一個PHP擴充。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.