PHP extension Development-Kernel execution process and extension structure

Source: Internet
Author: User
Tags sapi zts zend

Before developing the extension, it is best to understand the execution process of the PHP kernel, PHP includes three aspects:

SAPI
Zend VMS
Internal expansion

    • The Zend VM is a PHP virtual machine, similar to the JVM, and is the core of the compilation/execution of the respective language. They will be the respective code first compiled into an intermediate code, PHP is usually called Opcode,java is usually called bytecode, the difference is that PHP opcode directly by the Zend VM execution unit calls the corresponding C function execution, will not show the retention (can be cache), Java is usually generated as a class file to keep. This may also be the origin of the name of PHP interpreter. In fact, the relatively strict C + + and other compiled language, PHP and Java More is a combination of compiled and explanatory style.
    • SAPI can be seen as a way and specification for Zend VMs to provide services for compiling/executing PHP code to the outside world. Whether you are interacting with other programs as cli/cgi/fastcgi/apache_mod or embedded in other languages, such as C + +, can be implemented through SAPI specifications. One of its important data structures is sapi_module_struct (main/sapi.h line 217)
    • The internal extensions can be seen as libraries built on Zend VMs and SAPI, providing PHP developers with performance and ease-of-use assurance. Java's various packages/python the various modules function Similarly, the difference is in PHP for performance is implemented by C extension, similar in Java can be implemented by JNI, Python such as _socket and _select (multiplexing) is not native Python implementation.
Life cycle

The life cycle of various SAPI or PHP itself may be coupled with other components such as Apache, followed by further elaboration. For the life cycle of the PHP extension, here's a picture to borrow. The process should be easy to understand, about the process, there is a lot of information on the Internet, no longer repeat. Some of the areas we need to be aware of to develop extensions can also correspond to some nodes in the diagram:

The definition of a global variable, usually a zend_modulename_globals
Initialization of modules, including module-level initialization of resource/class/constant/ini configuration
The initialization of the request, including some initialization related to a single request
The end of the request, cleaning up the data/memory associated with a single request
Module offload, Cleanup module related data/memory

Basically all we have to do is follow the above process, implement the relevant built-in functions, define your own resources/global variables/classes/functions, etc. It is important to note that multiple process multithreading related issues should be taken care of when embedding other languages such as Python or embedding other components such as Apache.

PHP extension Structure

Use Php-src/ext/ext_skel to build a framework for PHP extensions

./ext_skel --extname=myext[[email protected] ~/software/needbak/php-5.5.2012:24]$==> ls myext/config.m4  config.w32  CREDITS  EXPERIMENTAL  myext.c  myext.php  php_myext.h  tests

The more important file is config.m4 (and of course the source code), the Config.m4 file can use the Phpize command to generate the Configure file, which explains whether we open the module and externally dependent libraries.

config.m4//If your extension relies on other external libraries dnl Php_arg_with (Myext, forMyext SUPPORT,DNL Make sure, the comment is aligned:dnl [--with-myext Include myext Support])//extension does not depend on external library D           NL php_arg_enable (Myext, whether to ENABLE Myext support,dnl Make sure so the comment is aligned:dnl [--enable-myext Enable Myext Support]//Find and Include header filesifTest"$PHP _myext"!="No"; ThenDNL Write More examples of tests ... dnl#--with-myext, check With-pathDNL search_path="/USR/LOCAL/USR"     # You might want to the change thisDNL search_for="/include/myext.h"  # likely want to change thisDnlifTest-r$PHP _myext/$SEARCH _for; Then # Path given as parameterDNL myext_dir=$PHP _myextDnlElse # Search Default Path listDNL ac_msg_checking ([ forMyext filesinchDefault path]) DNL forIinch $SEARCH _path; DoDnlifTest-r$i/$SEARCH _for; ThenDNL myext_dir=$iDNL Ac_msg_result (foundinch $i) DNLfiDnl DoneDnlfiDNL DNLifTest-z"$MYEXT _dir"; ThenDNL Ac_msg_result ([not found]) dnl ac_msg_error ([Please reinstall the Myext distribution]) DNLfiDnl#--with-myext, add include pathDNL Php_add_include ($MYEXT _dir/include)//loading lib position dnl#--with-myext Check for Lib and symbol presenceDNL Libname=myext# want to change thisDNL Libsymbol=myext# likely want to change thisDNL Php_check_library ($LIBNAME,$LIBSYMBOL, DNL [Dnl Php_add_library_with_path ($LIBNAME,$MYEXT _dir/$PHP _libdir, Myext_shared_libadd) dnl ac_define (Have_myextlib,1, []) dnl],[dnl ac_msg_error ([wrong Myext Lib version or Lib not found]) DNL],[dnl-l$MYEXT _dir/$PHP _libdir-LM DNL] dnl dnl php_subst (myext_shared_libadd) php_new_extension (Myext, myext.c,$ext _shared)fi
//php_myext.h#ifndef Php_myext_h#define PHP_MYEXT_Hextern zend_module_entry Myext_module_entry;#define PHPEXT_MYEXT_PTR &myext_module_entry//export symbols, useful when linking#ifdef Php_win32# define PHP_MYEXT_API __declspec (dllexport)#elif defined (__gnuc__) && __gnuc__ >= 4# define PHP_MYEXT_API __attribute__ ((Visibility ("default" ))#else# define PHP_MYEXT_API#endif#ifdef ZTS#include "TSRM.h"#endif//Declaration of several core functionsPhp_minit_function (Myext); Php_mshutdown_function (Myext); Php_rinit_function (Myext); Php_rshutdown_function (Myext); Php_minfo_function (Myext);//auto-generated test function declaration, our own definition of the module function need to declare thisPhp_function (confirm_myext_compiled);//global variable in this definition, expanded after IS zend_myext_globals structure bodyZend_begin_module_globals (Myext)LongGlobal_value;Char*global_string; Zend_end_module_globals (Myext)//How to get global variables under thread safety and non-thread safety#ifdef ZTS#define MYEXT_G (v) tsrmg (myext_globals_id, zend_myext_globals *, v)#else#define MYEXT_G (v) (MYEXT_GLOBALS.V)#endif#endif/* Php_myext_h * /
//myext.c#ifdef Have_config_h#include "config.h"#endif#include "php.h"#include "php_ini.h"#include "ext/standard/info.h"#include "php_myext.h"//global variable declarationZend_declare_module_globals (Myext)/ * True global resources-no need for thread safety here * /Static intLe_myext;//export of module functionsConstZend_function_entry myext_functions[] = {Php_fe (confirm_myext_compiled, NULL)/ * For testing, remove later. * /   Php_fe_end /* Must be the last line in myext_functions[] * /};//Module structureZend_module_entry Myext_module_entry = {#if zend_module_api_no >= 20010901Standard_module_header,#endif    "Myext", Myext_functions, Php_minit (Myext), Php_mshutdown (Myext), Php_rinit (Myext),/ * Replace with NULL if there 's nothing to do at request start */Php_rshutdown (Myext),/ * Replace with NULL if there 's nothing to does at request end */Php_minfo (Myext),#if zend_module_api_no >= 20010901Php_myext_version,#endifStandard_module_properties};#ifdef Compile_dl_myextZend_get_module (Myext)#endifsettings for the//ini configuration filePhp_ini_begin () Std_php_ini_entry ("Myext.global_value"," A", Php_ini_all, Onupdatelong, Global_value, Zend_myext_globals, myext_globals) std_php_ini_entry ("Myext.global_string","Foobar", Php_ini_all, onupdatestring, global_string, Zend_myext_globals, Myext_globals) php_ini_end ()//Initialize global variablesStatic voidPhp_myext_init_globals (Zend_myext_globals *myext_globals) {myext_globals->global_value =0; myext_globals->global_string = NULL;}//function when module is loadedPhp_minit_function (Myext) {/* If You have INI entries, uncomment these lines register_ini_entries (); */    returnSUCCESS;}//Module unload time functionPhp_mshutdown_function (Myext) {/* Uncomment if you have INI entries unregister_ini_entries (); */    returnSUCCESS;}//Request initialization functionPhp_rinit_function (Myext) {returnSUCCESS;}//Request Close functionPhp_rshutdown_function (Myext) {returnSUCCESS;}//module information, PhpinfoPhp_minfo_function (Myext) {Php_info_print_table_start (); Php_info_print_table_header (2,"Myext Support","Enabled"); Php_info_print_table_end ();/* Remove Comments If you had entries in php.ini display_ini_entries (); */}//Test functionPhp_function (confirm_myext_compiled) {Char*arg = NULL;intArg_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. ","Myext", ARG); Return_stringl (STRG, Len,0);}

PHP extension Development-Kernel execution process and extension structure

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.