PHP extension Development (1): Getting Started

Source: Internet
Author: User
Tags php source code sapi

PHP extension Development of the article, blog has been many, more classic is:

    1. Tipi project (http://www.php-internals.com/, highly recommended)
    2. "Extending and Embedding PHP" (Chinese translation see http://www.walu.cc/phpbook/, highly recommended)
    3. "PHP core technology and best practices," a chapter dedicated to the development of PHP extension, but the version is older, for reference.
    4. The PHP5 authoritative guide also has a chapter devoted to PHP's extended development.

I'm going to summarize my learning and understanding of PHP Extension Development in this series, trying to simply and clearly describe the basics of developing a PHP extension in a Linux system. The level is low, inevitably has the mistake, hoped to point out.

Preparatory work

Start by getting a copy of the PHP source code (you can check it out on GitHub, or download the latest stable version on the official website) and compile it. To speed up the compilation, we recommend disabling all additional extensions (using the--disable-all option), but it's a good idea to turn on debug (using the--enable-debug option) and thread safety (using--ENABLE-MAINTAINER-ZTS). However, to turn off debug when publishing the extension, choose whether to turn on thread safety as appropriate:

$./buildconf--force$. /configure--disable-all--enable-debug--enable-maintainer- make

Note that I did not specify the--prefix option (and also no make install), because this is not required. Note that if you look at the output information, you may need to install some dependent packages to successfully compile PHP.

Compiled PHP executable program in the source code of the SAPI directory, corresponding to different host environments have different subdirectories, we will use the CLI (Command line interface) environment, we can build an alias for easy reference:

$ alias php-dev=/usr/local/src/php-5.6. 5/sapi/cli/php

There are a few command-line options that are useful:

Php-dev-H # Print help information php-dev-v # print version info php-dev--INI # Print configuration information        PHP-D EV-m # Print loaded module information PHP-dev-I # phpinfophp-dev-r <code> # Execute code

Extended skeleton

All the official extensions of PHP are in the Ext directory of the source code, and the extensions we write ourselves can be placed in that directory. Note that this directory has a shell script named Ext_skel, which is used to generate the PHP extension skeleton, which can help us to quickly create a PHP extension:

$./ext_skel--extname=myext

The above command helped us create an extension called Myext, the source code in the Myext directory. Execution of the script without any parameters can print help information so that you can see more options available to the script.

Next, let's finish our expansion. Go to the Myext directory, edit the CONFIG.M4 configuration file, find the Php_arg_enable macro function, and remove the previous DNL comment (three lines). Return to the source root and re-execute the buildconf, configure, and make commands:

$./buildconf--force$. grep Myext     --enable-myext           enable Myext support$. /configure--disable-all--enable-myext--enable-debug--enable-maintainer- make

Note that we use the./configure--help | grep Myext Prints the loading of our extensions, and if we don't see the output below, our extension is not configured successfully, and we look back at the config.m4 file.

This compilation should be very fast because most of the code has already been compiled. PHP has another way of compiling extensions (using dynamic connections to compile extensions into. so files), but we recommend using static compilation when developing extensions, because this eliminates the step of loading extensions in the configuration file.

If all goes well, our first extension is ready for execution:

grep myextmyext$ PHP ' Echo confirm_myext_compiled ("Myext"). "\ n"; ' Congratulations! You have successfully modified EXT/MYEXT/CONFIG.M4. Module Myext is now compiled to PHP.

The first command shows that our extension has been loaded. The second command executes the function that the Ext_skel extension skeleton automatically created for us. Of course, this function is meaningless, but we can easily adapt this function to Hello World .

Create an extension manually

Most tutorials are developed with the Ext_skel extension skeleton as a prototype, which is of course convenient and quick. But I personally prefer a purely manual way of developing extensions, because it's easier to understand every detail.

To create an extension manually, first go to the EXT directory and create our extension directory myext2. There are several files that are required: config.m4,myext2.c and php_myext2.h.

First, let's write the configuration file config.m4:

Php_arg_enable (MYEXT2, whether to enable MYEXT2 support,[  --enable-myext2           enable MYEXT2 support  ])if test "php_myext2"! = "No";  then   Php_new_extension (Myext2, myext2.c, $ext _shared)fi

CONFIG.M4 is actually the configuration file used by the autoconf program, autoconf is an important component in the Autotools Toolbox. It takes a long time to fully introduce the usage of autoconf, but the usage here is very simple.

Php_arg_enable is a macro function defined by PHP for autoconf, MYEXT2 is its first parameter, which indicates the name of the extension, and the next two parameters are only used to display when make and configure are executed, so we can write it casually. [] In the autoconf syntax, the function is similar to double quotation marks, used to wrap a string (note that the second argument contains a space, but you can use no square brackets). There is also a fourth parameter to indicate whether the extension is on or off by default (yes or no) and no by default.

The following three lines are actually shell syntax, to determine whether we have opened the PHP_MYEXT2 extension module. If the extension (--ENABLE-MYEXT2) is turned on, the value of the $PHP_MYEXT2 variable is not no, so the Php_new_extension macro is executed. This macro function is also the extension syntax defined by PHP for autoconf, the first parameter is also the extension name, the second parameter is the extension to compile the C file, if there are more than one, then write down (space delimited), the third parameter is fixed is $ext_shared.

Next write the php_myext2.h header file, the name of the file is the PHP extension specification-php_ extension. h:

1 #ifndef Php_myext2_h2 #definePhp_myext2_h3 4 externzend_module_entry myext2_module_entry;5 #definePhpext_myext2_ptr &myext2_module_entry6 7 #definePhp_myext2_version "0.1.0"8 9 /*prototypes*/Ten php_function (hello); One  A #endif/* Php_myext2_h */

The main code here is to define a macro named Phpext_myext2_ptr, which is referenced by the PHP bottom to refer to our extensions. As you can see, the name of the macro is also the canonical-phpext_ extension _ptr. And Myext2_module_entry is the struct that we will define later in the. c file, and its name is also canonical-extension _module_entry.

We also define a macro that identifies our extension version number and a function prototype (through the Php_function macro, the parameters of the Php_function macro function are externally available function names), which we will implement later.

Finally, consider the implementation of the myext2.c file:

1#include"Php.h"2#include"php_myext2.h"3 4 /*{{{myext2_functions[]5  *6 * Every user visible function must has a entry in myext2_functions[].7  */8 Static ConstZend_function_entry myext2_functions[] = {9 Php_fe (Hello, NULL)Ten Php_fe_end One }; A /* }}} */ -  - /*{{{ myext2_module_entry the  */ -Zend_module_entry Myext2_module_entry = { - Standard_module_header, -     "myext2",/*Module Name*/ +Myext2_functions,/*module Functions*/ -Null/*Module Initialize*/ +Null/*Module Shutdown*/ ANull/*Request Initialize*/ atNull/*Request Shutdown*/ -Null/*Phpinfo*/ -Php_myext2_version,/*Module Version*/ - standard_module_properties - }; - /* }}} */ in  - #ifdef COMPILE_DL_MYEXT2 to zend_get_module (MYEXT2) + #endif -  the /*{{{proto void Hello () * Print "Hello world!"*/ $ php_function (Hello)Panax Notoginseng { -php_printf ("Hello world!\n"); the } + /* }}} */

In contrast to the. c files created by the extended skeleton, we will find that our. c files are very simple, but they are enough for a basic extension.

The code above is simple and clear, and most of the comments are already very descriptive. Let us briefly summarize the following:

    1. Start with the header file that we want to use. Php.h is a must, it has helped us to include the vast majority of the standard library files we will use, such as stdio.h,stdlib.h and so on.
    2. Myext2_functions defines an array of structures that are composed of the functions we want to expose, each of which is specified by a PHP_FE macro. The PHP_FE macro has two parameters, the first is the function name that can be used externally, the second is the parameter information (here we simply use NULL), and the last element must be php_fe_end. Note its comments, emphasizing again that each function to be exposed to external use must be defined in the struct array.
    3. Myext2_module_entry defines our module information, which is a struct, and most of the properties have been explained by comments. Note that the middle of the five function pointers, we are simply set to NULL, in the subsequent blog post will tell their usage.
    4. The Zend_get_module (MYEXT2) macro function is contained by a IFDEF macro, so it is determined whether it is invoked as appropriate. As to what circumstances will be invoked, what will not be called, in subsequent blog post will be narrated.
    5. The last few lines of code we implement the Hello function, it is very simple, call php_printf output Hello world! with a newline character, php_printf usage and printf exactly the same.
    6. The {{and}}} in the comments is used to facilitate the folding of the editor such as Vim, and we recommend that you write the comments as well.

This involves a number of macros, such as Php_fe,php_fe_end,php_function, and so on, the full introduction of these macros to follow the blog post can, the simplest way is to remember these macros.

Notice that the naming of each of our files, the naming of the variables, the spaces and indents, and the annotations are all very canonical, and following these specifications, we can make the code we write more in line with the code of PHP itself, and we recommend that you use such a specification to develop PHP extensions.

Finally, compile and run our extension:

$./buildconf--force$. grep myext2   --enable-myext2           enable Myext2 support$. /configure--disable-all--enable-myext2--enable-debug--enable-maintainer-make$ php grep myext2myext2$ PHP ' hello (); ' Helloworld!

PHP extension Development (1): Getting Started

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.