Home Backend Development PHP Tutorial PHP扩张模块结构

PHP扩张模块结构

Jun 13, 2016 pm 01:16 PM
module php quot test zend

PHP扩展模块结构

所有PHP扩展遵循一个共同的结构

1、头文件包含(包括所有需要的宏、API)
2、C声明导出函数
3、声明Zend函数块

一、头文件包含

通过ext_seketon新建的扩展,默认都会新建一个php_extname.h的头文件。其中包含了
php.h,该文件导入Zend基本的宏和API。
二、声明导出函数

ZEND_FUNCTION(my_function),提供PHP中调用的函数。
展开此宏:
void zif_my_function(INTERNAL_FUNCTION_PARAMETERS)
void zif_my_function(int ht, zval *return_value, zval *this_ptr, int return_value_users, zend_executor_globals *executor_globals);
参数的作用:
参数 描述
ht 接收的参数个数。考虑向后兼容,使用ZEND_NUM_ARGS()来代替ht
return_value 传递到PHP接口的返回值。
this_ptr 如果这个函数是对象中的方法,this_ptr返回当前对象
return_value_used 标志最终这个函数返回到PHP接口中是否被使用。
executor_globals 指向zend引擎的全局设置。

三、声明Zend函数块

建立zend_function_entry数组,提供给ZEND作为PHP的接口。    

typedef struct _zend_function_entry {
    char *fname;
    void (*handler)(INTERNAL_FUNCTION_PARAMETERS);
    unsigned char *func_arg_types;
} zend_function_entry;
Copy after login
参数 描述
fname 提供给PHP中调用的函数名。例如mysql_connect
handler 负责处理这个接口函数的指针。
func_arg_types 标记参数。可以设置为NULL
static const zend_function_entry mysql_functions[] = {
                PHP_FE(mysql_connect,  arginfo_mysql_connect)
                PHP_FE(mysql_pconnect,  arginfo_mysql_pconnect)
                PHP_FE(mysql_close,  arginfo__optional_mysql_link)
                PHP_FE(mysql_select_db,  arginfo_mysql_select_db)
     {NULL, NULL, NULL}
}
Copy after login

上述是mysql扩展中定义的zend_function_entry的部分。其中{NULL, NULL, NULL}标志数组的结束


四、声明Zend模块扩展结构

此块信息必须存储在zend_module_entry结构中,包含模块的必要信息。例如,初始化模块函数指针,模块的名称,版本信息等。

struct _zend_module_entry {
    unsigned short size;
    unsigned int zend_api;
    unsigned char zend_debug;
    unsigned char zts;
    char *name;
    zend_function_entry *functions;
    int (*module_startup_func)(INIT_FUNC_ARGS);
    int (*module_shutdown_func)(SHUTDOWN_FUNC_ARGS);
    int (*request_startup_func)(INIT_FUNC_ARGS);
    int (*request_shutdown_func)(SHUTDOWN_FUNC_ARGS);
    void (*info_func)(ZEND_MODULE_INFO_FUNC_ARGS);
    char *version;
    [more]
};
Copy after login

typedef struct _zend_module_entry zend_module_entry;
Copy after login

参数 描述
size, zend_api, zend_debug and zts 通常使用STANDARD_MODULE_HEADER来填充,
name 扩展的名称
functions 指向zend_functions_entry指针
module_startup_func 模块初始化时被调用的函数指针。用来放一些初始化步骤。初始化过程中出现故障返回FAILURE,成功返回SUCCESS。声明一个初始化函数使用ZEND_MINIT
module_shutdown_func 模块被关闭时调用的函数指针,同来用来做一次性的析构步骤。如释放资源。
成功返回SUCESS,失败返回FAILURE,未使用返回NULL。声明使用ZEND_MSHUTDOWN
request_startup_func 每处理一次请求前调用此函数。成功SUCESS,失败FAILURE,未使用返回NULL。声明使用ZEND_RINIT。
从WEB来解释,就是每次请求调用此函数。
request_startup_func 每处理一次请求前后调用此函数。成功SUCESS,失败FAILURE,未使用返回NULL。声明使用ZEND_RINIT。
request_shutdown_func 每处理一次请求结束后调用此函数。成功SUCESS,失败FAILURE,未使用返回NULL。声明使用ZEND_RSHUTDOWN。
info_func 当调用phpinfo()时打印出的关于此扩展的信息。
这个信息就是由此函数来输出的。
声明使用ZEND_MINFO
version 扩展的字符串版本号。若无版本号,可以使用NO_VERSION_YET
[more] 多余不重要的参数,可以使用宏STANDARD_MODULE_PROPERTIES_EX或STANDARD_MODULE_PROPERTIES
zend_module_entry firstmod_module_entry =
{
    STANDARD_MODULE_HEADER,
    "New Module",
    firstmod_functions,
    NULL, NULL, NULL, NULL, NULL,
    NO_VERSION_YET,
    STANDARD_MODULE_PROPERTIES,
};
Copy after login

这是一个最基本的模块结构,模块名“New Module”,函数列表为firstmod_functions,未设置startup、shutdown函数


下面是名为test的PHP扩展的文件,通过上面的介绍,对比下面的代码,就会比较清晰的理解PHP扩展开发的步骤。


#ifdef HAVE_CONFIG_H
#include "config.h"
#endif


/*包含ZEND提供的API、宏和基本的PHP内置函数,例如php_trim*/
#include "php.h"
#include "php_ini.h"
#include "ext/standard/info.h"
#include "php_test.h"

/* 开启模块中的全局变量 */
ZEND_DECLARE_MODULE_GLOBALS(test)

/* True global resources - no need for thread safety here */
static int le_test;

/* 
* 声明函数数组,提供给PHP使用
*/
const zend_function_entry test_functions[] = {
     PHP_FE(my_function,     NULL)          /* For testing, remove later. */
     PHP_FE_END     /* Must be the last line in test_functions[] */
};
/* }}} */

/* 模块结构,声明了startup\shutdown、模块名及phpinfo打印时的函数
*/
zend_module_entry test_module_entry = {
#if ZEND_MODULE_API_NO >= 20010901
     STANDARD_MODULE_HEADER,
#endif
     "test",
     test_functions,
     PHP_MINIT(test),
     PHP_MSHUTDOWN(test),
     PHP_RINIT(test),          /* Replace with NULL if there's nothing to do at request start */
     PHP_RSHUTDOWN(test),     /* Replace with NULL if there's nothing to do at request end */
     PHP_MINFO(test),
#if ZEND_MODULE_API_NO >= 20010901
     "0.1", /* Replace with version number for your extension */
#endif
     STANDARD_MODULE_PROPERTIES
};

#ifdef COMPILE_DL_TEST
ZEND_GET_MODULE(test)
#endif

/* 从php.ini配置文件中读取配置信息 */
PHP_INI_BEGIN()
    STD_PHP_INI_ENTRY("test.global_value",      "42", PHP_INI_ALL, OnUpdateLong, global_value, zend_test_globals, test_globals)
    STD_PHP_INI_ENTRY("test.global_string", "foobar", PHP_INI_ALL, OnUpdateString, global_string, zend_test_globals, test_globals)
PHP_INI_END()


/* 初始化全局变量默认值 */
static void php_test_init_globals(zend_test_globals *test_globals)
{
     test_globals->global_value = 0;
     test_globals->global_string = NULL;
}


/* 模块第一次加载时被调用
*/
PHP_MINIT_FUNCTION(test)
{
     /* 注册全局变量 */
     REGISTER_INI_ENTRIES();
     
     return SUCCESS;
}

/* 模块关闭时调用
*/
PHP_MSHUTDOWN_FUNCTION(test)
{
     /* 释放全局变量 */
     UNREGISTER_INI_ENTRIES();
     
     return SUCCESS;
}

/* 每次请求前调用
*/
PHP_RINIT_FUNCTION(test)
{
     return SUCCESS;
}

/* 
/* 每次请求结束时调用
*/
PHP_RSHUTDOWN_FUNCTION(test)
{
     return SUCCESS;
}

/* phpinfo()输出扩展信息
*/
PHP_MINFO_FUNCTION(test)
{
     php_info_print_table_start();
     php_info_print_table_header(2, "test support", "enabled");
     php_info_print_table_end();

     /* 是否输出php.ini中的配置信息
     DISPLAY_INI_ENTRIES();
     */
}


/* 定义函数my_function提供给PHP中使用 */
PHP_FUNCTION(my_function)
{
     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.", "test", arg);
     RETURN_STRINGL(strg, len, 0);
}
Copy after login
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles