PHP development of the first extension

Source: Internet
Author: User
Tags sapi zts

First declare: We are going to build an extension or a module named Hello_module. This module provides a method: Hello_word.


First, the construction of PHP environment


1) generally use the source package to compile the installation, rather than binary package installation. Because there are some adventures in using PHP's binary bundle installation, these versions tend to ignore. Two important options for/configure, which are facilitated during development:

The first of the--enable-debug. This option compiles the additional symbolic information into the PHP execution file so that if a segment error occurs, you can get a kernel dump file from it, use GDB to trace and discover where and why a segment error occurred.


2) Another option depends on your PHP version. in php 4.3, this option is named--enable-experimental-zts and is--enable-maintainer-zts in PHP 5 and later versions. This option allows PHP to assume that it executes in a multithreaded environment and allows you to catch common program errors, but they are harmless in non-multithreaded environments, making your extensions unsafe for multithreaded environments. Once you have compiled PHP with these additional options and installed it on your development server (or workstation), you can add your first extension to it.

3) The Zend engine provides a memory manager with the ability to track memory leaks in the extension and provides detailed debugging information. Tracing is disabled by default and is thread-safe. To open, you should pass the--enable-debug and--ENABLE-MAINTAINER-ZTS options along with the other common options to configure. For instructions on building PHP from source code, see the instructions for considerations before you install.

A typical configure command line might look like this:

$./configure--prefix=/usr/local/php--enable-debug--enable-maintainer-zts  

1) PHP can generally be installed in the/usr/local/php directory.
2) PHP binaries are in the/usr/local/php/bin directory, including PHP's own tools phpize.

Phpize is actually a shell script that can be used to view its contents with VI phpize.
Note: Use Phpize to install autoconf macros. Because the Config.m4 file is written using the GNU autoconf syntax. In short, a shell script that is enhanced with a powerful macro language. Comments are delimited by the string dnl, and the strings are placed between the left and right square brackets (for example, [and]). Strings can be nested as many references as needed. The complete syntax reference can be found in the http://www.gnu.org/software/autoconf/manual/
The simplest way to install autoconf macros: Apt-get install autoconf

2, Ext_skel script

php extension consists of several files that are common to all extensions. A lot of the details of these files are similar between different extensions, but it's just a struggle to replicate the contents of each file. Fortunately, there are scripts that can do all the initialization work, called Ext_skel, which is distributed with PHP 4.0.

./ext_skel--extname=module [--proto=file] [--stubs=file] [--xml[=file]]             [--skel=dir] [--full-xml] [--no-help]    --extname=module   Module is the name of your extension    --proto=file       file contains prototypes of Functions to create    --stubs=file       generate = function stubs in file    --xml              generate XML documentation To is added to Phpdoc-cvs    --skel=dir         path to the skeleton directory    --full-xml         generate XML Documentation for a self-contained extension                       (not yet implemented)    --no-help          don ' t try to be nice and creat E comments in the Code and                       helper functions to test if the module compiled  

When developing a new extension, only the parameters you need to focus on are--extname and--no-help. Unless you are already familiar with the extended structure, do not want to use--no-help; Specifying this parameter causes Ext_skel not to omit many useful comments in the generated file.

The rest of the--extname will pass the extended name to Ext_skel. "Name" is an all-lowercase identifier that contains only letters and underscores, and is unique under the ext/folder of the PHP release package.

The--proto option allows a developer to specify a header file that creates a series of PHP functions, ostensibly to develop an extension based on a library of functions, but rarely works for most of the head-modern files. If you use the Zlib.h header file for testing, it will result in a large number of empty and meaningless prototype files in the Ext_skel output file. The--xml and--full-xml options currently do not work at all. The--skel option can be used to specify a set of modified frame files to work, which is outside the scope of this section of the topic.

3. Expand the composition file

Whether by hand, through Ext_skel, or through another extension generator, all extensions will have the following file:
1) config.m4:phpize

The configuration file configure option, which is used to prepare which extensions of the system to build, is the UNIX build system configuration.
The corresponding win system is config.w32:http://www.php.net/manual/zh/internals2.buildsys.configunix.php
2) Php_hello_module.h:

Header file containing references when the extension is built as a static module and placed in a PHP binary package, the build system requires that the header file named with the Php_ extension contain a pointer definition to the extension structure. Like other header files, this file often contains additional macros, prototypes, and global quantities. Of course you can put your head file content at the top of the source file hello_module.c. Separating is just making the code easier to organize, and it's a good habit.
3) Hello_module.c:
source file containing module functions
The extension should contain any number of header files, source files, unit tests, and other supporting files, and this four files are only enough to make up the smallest extension. The list of files for the hello_module extension is as follows:

ext/hello_module/  config.m4        config.w32        CREDITS        experimental       php_hello_module.h        hello_ MODULE.C        tests/         

4. Interacting with the UNIX build system: CONFIG.M4
 The config.m4 file is responsible for resolving configure command-line options at configuration time. This means that it will check the required external files and do some similar tasks for configuration and installation. The Config.m4 file tells the UNIX build system which extensions configure options are supported, which extension libraries you need, and which source files to compile as part of it. For all commonly used autoconf macros, including PHP-specific and autoconf built-in,
config.m4 File Examples
DNL $Id $ dnl config.m4 for extension example Php_arg_with (example, for example support, [--with-example[=file] Include example Support. File is the optional path to Example-config]) php_arg_enable (example-debug, whether to ENABLE debugging support in Exampl E, [--enable-example-debug example:enable debugging support in example], no, no) Php_arg_with (Example-extra, F or extra libraries for example, [--with-example-extra=dir example:location of extra libraries for example], no, n O) DNL detects if the extension is enabled if test "$PHP _example"! = "no"; Then DNL detects Example-config. Try the given path first, and then look for ac_msg_checking in the $PATH ([for Example-config]) example_config= "example-config" if test "$PHP _example"! = "Yes"; Then example_path= $PHP _example Else example_path= ' $php _shtool PATH $EXAMPLE _config ' fi dnl If you find an available example-config, use it if test-f "$EXAMPLE _path" && test-x "$EXAMPLE _path" && $EXAMPLE _path--version >/dev/null 2>&A mp;1; Then Ac_msg_result ([$EXAMPLe_path]) example_lib_name= ' $EXAMPLE _path--libname ' example_incdirs= ' $EXAMPLE _path--incdirs ' example_libs= ' $ Example_path--libs ' DNL detects if the extension library is working properly php_check_library ($EXAMPLE _lib_name, example_critical_function, [dnl Add required I Nclude directory Php_eval_incline ($EXAMPLE _incdirs) DNL Add the required extension libraries and the directory where the extensions are located php_eval_libline ($EXAMPLE _libs, Example_shared_ Libadd)],[DNL jumps out of the ac_msg_error ([Example Library not found.  Check Config.log for more information.]) ],[$EXAMPLE _libs]) Else DNL does not have an available example-config, jump out of Ac_msg_result ([not found]) ac_msg_error ([please check your examp  Le installation.]) Fi DNL detects if debugging is enabled if test "$PHP _example_debug"! = "no"; Then DNL Yes, then set the C language macro directive ac_define (Use_example_debug,1,[include debugging in EXAMPLE]) Fi DNL detects additional support if test " $PHP _example_extra "! =" no "; Then if test "$PHP _example_extra" = = "yes"; Then Ac_msg_error ("must specify a path when using--with-example-extra]) fi php_check_library (Example-extra, ex Ample_critical_extRa_function, [DNL adds the required path Php_add_include ($PHP _example_extra/include) Php_add_library_with_path (Example-extra, $ Php_example_extra/lib, Example_shared_libadd) ac_define (have_exampleextralib,1,[whether Example-extra support is Present and requested]) example_sources= "$EXAMPLE _sources example_extra.c"],[ac_msg_error ([Example-extra Lib not Found.  See Config.log for more information.]) ],[-l$php_example_extra/lib] fi DNL Finally, information such as the extension and its required files are passed to the build system Php_new_extension (EXAMPLE, example.c $EXAMPLE _sources, $ex   t_shared) Php_subst (Example_shared_libadd) fi

Note: Any comment with the DNL prefix is not parsed.

4.1 php_arg_*: Give user-selectable options

in the CONFIG.M4 example above, after two comments, 3 lines of code were first seen, using Php_arg_with () and php_arg_enable (). These give configure the option, and the help text to display when running./configure--help. As the name implies, the difference between the two is whether to create the--with-* option or the--enable-* option. Each extension should provide at least one more option and an extension name so that the user can choose whether to build the extension into PHP. By convention, Php_arg_with () is used to obtain options for parameters, such as extending the location of the desired library or program, while Php_arg_enable () is used to represent the options for a simple flag.

No matter which command you use, you should comment out the other one. In other words, if you use –enable-my_module, you should remove –with-my_module. Vice versa.
Configue Use example:./configure--enable-hello_module
it will

DNL php_arg_enable (Hello_module, whether to Enablehello_module SUPPORT,DNL make sure that's comment is ALIGNED:DNL [--e Nable-hello_module Enablehello_module support]) modified into php_arg_enable (Hello_module, whether to Enablehello_module , Dnl Make sure, the comment are aligned:[--enable-hello_module enablehello_module support])


4.2 Handling User Selection

CONFIG.M4 can give users a choice of what to do, and now is the time to make a choice. In the example above, the three options are clearly default to "no" when not specified. It is customary to use this value as the default value for the option to enable the extension, and to overwrite this value with Phpize for extensions that are built separately from PHP, while building in PHP should not be left out of scope by default. The code to handle these three options is much more complex.

--with-example[=file] Option

First detect if the--with-example[=file] option is set. This option is not specified, or uses a negative format (--without-example), or is assigned a value of "no" when it controls the entire extension of the containing object other things will not happen. The value specified in the example above is/some/library/path/example-config, so the first Test succeeds.

Next, the code calls ac_msg_checking (), which is a autoconf macro that outputs a standard line such as "CHECKING for ..." Information and detects if the user assumes that the Example-config is a clear path. In this example, Php_example takes a value of/some/library/path/example-config, which is now copied to the Example_path variable. The code is executed only if the user has specified--with-example $php _shtool path $EXAMPLE _config, attempting to speculate on the location of the example-config using the user's current PATH environment variable. In any case, the next step is to detect whether the selected Example_path is a normal file, executable, and successful. If successful, call Ac_msg_result () to end the output line starting with ac_msg_checking (). Otherwise, call Ac_msg_error (), print the information given, and immediately break execution configure.

The code now executes several example-config to determine some site-specific configuration information. The next call is Php_check_library (), a macro provided by the PHP build system that wraps the autoconf ac_check_lib () function. Php_check_library () attempts to compile, link, and execute a program, invoke the symbol specified by the second parameter in the library specified in the first parameter, and use the string given in the fifth argument as an additional link option. If the attempt succeeds, the script given by the third parameter is run. This script tells PHP to build the system by taking the header file path, library file path, and library name from the original option string provided by Example-config. If an attempt fails, the script runs the script in the fourth parameter. This calls Ac_msg_error () to interrupt program execution.


--enable-example-debug Options
Handling--enable-example-debug is simple. Simply detect its true value. If the detection succeeds, call Ac_define () to make the C-language macro directive use_example_debug the source code that is available for the extension. The third parameter is a comment string to config.h, which is usually left blank.


--with-example-extra=dir Options
For this example, the assumed "extra" feature action requested by the--WITH-EXAMPLE-EXTRA=DIR option is not shared with the assumed Example-config program, and there is no default search path. Therefore, the user needs to provide the Setup program before the desired library. It's a little bit like a reality extension, where the settings just play a descriptive role.

The code begins to detect the true value of the Php_example_extra in a familiar way. If the provided is in a negative form, no additional processing is done and the user does not request additional functionality. Call Ac_msg_error () to abort processing if the supplied is a positive form of a parameter that is not supplied. The next step is to call Php_check_library () again. This time, because there are no predefined compilation options available, Php_add_include () and Php_add_library_with_path () are used to build the header file path, library file path, and library flags required for additional functionality. Also call Ac_define () to indicate that the requested extra function code is available, set the variable to tell later code, and have additional source code to build. If the detection fails, the familiar Ac_msg_error () is called. Another way to handle the failure is to change to call Ac_msg_warning (), for example:

4.3 php_new_extension macro

By default, CONFIG.M4 created by Ext_skel can accept instructions, and the extension is automatically enabled. Enabling the extension is done by php_extension this macro. If you want to change the default situation and want the user to explicitly use the –enable-my_module or –with-my_module instructions to include the extension in the PHP binaries, then "if test" $PHP _my_module "! =" No " Change to "if test" $PHP _my_module "= =" yes ".

if test "$PHP _my_module" = = "yes"; Thendnl      


This will cause the user to be required to use the –enable-my_module instruction every time the PHP is reconfigured and compiled.

Php_new_extension ()
Is that the macro tells the build system to build the extension itself and the files it uses.

Php_new_extension () Parameter:

The first parameter is the name of the extension, and the directory that contains it. The second parameter is a list of all source files that are part of the extension, see Php_add_build_dir () for information about adding source files to the build process in subdirectories. The third parameter is always $ext _shared, and the value of the parameter is determined by configure when calling Php_arg_with () for--with-example[=file]. The fourth parameter specifies a "SAPI class", only for extensions that specifically require CGI or CLI SAPI. Other cases should be left blank. The fifth parameter specifies a list of flags to be added to the CFLAGS at build time. The sixth parameter is a Boolean value, and "yes" forces the entire extension to be built using $CXX instead of $CC. All parameters after the third are optional. Finally, call PHP_SUBST () to enable the extended shared build.

For example, we want to build an extension that is Hello_module

DNL $Id $  dnl config.m4 for extension Hello  php_arg_enable (hello, whether to ENABLE hello support,  [  -- Enable-hello           Enable Hello support])  if test "$PHP _hello"! = "no"; then  php_new_extension (Hello_module, HELLO_MODULE.C, $ext _shared)  fi  

5, the specific build extension

The first step is to generate the code
PHP provides a tool ext_skel similar to the code generator for ease of development and can be found in the instructions.
First we create a file Helloworld.skel,

Its contents are executed as String GetString (String str):./ext_skel--extname=helloworld--proto=helloworld.skel

1. Svnignore when developed in SVN collaboration mode, the file is not recognized by SVN by default. 2. Experimental this file is used to identify and record the development logs, alerts, prompts and other relevant information before the release of the stable version. It should be deleted when it is officially released. 3, Config.w32 in the Windows environment to use the configuration file, usually need to be modified. 4, CONFIG.M4 in the Linux/unix environment to use the configuration file, usually also need to modify. 5, phpext.c default contains the basic extension example of the source code, that is, by default, extended codes are written in this area. 6, Php_phpext.h Extension of the source file contains the header file, which contains the definition of the function. 7, CREDITS first line to write the extension of the name, the second line to write the name of the participants, multiple separated by commas. 8, phpext.php a used to test the extension is normal loading, working PHP files, according to the actual situation modified. 9. The data or files associated with the extension test will be stored by default in the Tests folder.

At this point, the HelloWorld code framework for this extension is already out.


Step two, modify the configuration
Then modify the config.m4 file to delete the first dnl of 10, 11, 123.

DNL Php_arg_with (HelloWorld, for HELLOWORLDSUPPORT,DNL Make sure that's comment is ALIGNED:DNL [  --with-helloworld< C2/>include HelloWorld support]) modified to Php_arg_with (HelloWorld, for HelloWorld Support,make sure that the  comment is aligned:[  --with-helloworld     Include HelloWorld support   ])


The third step is to realize the function


Modify the source Helloworld.c file, find getstring This function to change to

Php_function (getstring) {    char *str = NULL;    int argc = Zend_num_args ();    int str_len;    char *result;    if (Zend_parse_parameters (argc tsrmls_cc, "s", &str, &str_len) = = FAILURE)        return;    Str_len = spprintf (&result, 0, "%s", str);    Return_stringl (result, str_len, 0);}


Fourth step, compiling the extension

Phpize./configure--with-php-config=/usr/local/php/bin/php-configmake && make install

Fifth step, add the extension
At this point, all goes well, the extension is already in the modules/ccvita.so position. The following is to add this extension to PHP, so that we can invoke the PHP program.

vim/usr/local/php/etc/php.iniextension=helloworld.so #在php. ini file finally adds this line of service php-fpm restart #重启PHP服务


PHP development of the first extension

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.