Translation [PHP extension development and Embedded] Chapter 18th-php Extension Auto-generation

Source: Internet
Author: User
Tags cdata pear php online php source code types of functions


Extended Build

There is no doubt that you have noticed that each PHP extension contains some very common and very monotonous structures and files. When starting a new extension development, if these public structures already exist, it is meaningful to consider populating the function code only. To do this, a simple but useful shell script is included in PHP.

Ext_skel

Switch to the ext/directory under your PHP source code tree and execute the following command:

jdoe@devbox:/home/jdoe/cvs/php-src/ext/$./ext_skel Extname=sample7

Wait a minute, output some text, and you'll see the following output:

To use your new extension and you'll have to execute the following steps:1.  $ CD. 2.  $ VI ext/sample7/config.m43.  $./buildconf4.  $./configure [With|enable]-sample75.  $ make6.  $./php-f EXT/SAMPLE7/SAMPLE7.PHP7.  $ VI ext/sample7/sample7.c8.  $ makerepeat Steps 3-6 until you be satisfied with EXT/SAMPLE7/CONFIG.M4 Andstep 6 confirms this your module is compiled Into PHP. Then, start Writingcode and repeat the last of the steps as often as necessary.

Now look at the Ext/sample7 directory and you will see the annotated version of the extended skeleton code you wrote in the 5th chapter "Your first extension". Just now you can't compile it yet; But you just have to make a few changes to CONFIG.M4 to get it working so you can avoid most of the work you do in chapter 5th.

Generating function prototypes

If you are writing a wrapper extension to a third-party library, then you have a description of the machine-scale version of the function prototype and the basic behavior (header file), by passing an extra parameter to the./ext_skel, which will automatically scan your header file and create a simple php_ that corresponds to the interface Fucntion () block. The following is the parsing of the zlib header using the./ext_skel directive:

jdoe@devbox:/home/jdoe/cvs/php-src/ext/$./ext_skel Extname=sample8 \proto=/usr/local/include/zlib/zlib.h

Now in ext/sample8/sample8.c, you can see many php_function () definitions, one for each zlib function. Note that the skeleton generator generates warning messages for some unknown resource types. You need to pay particular attention to these functions, and in order to correlate these internal complex structures with user-space-accessible variables, you may need to use the knowledge you learned in Chapter 9th, "Resource data Types".

Pecl_gen

There is also a more sophisticated, but more complex code generator: Pecl_gen, which can be found in PECL (http://www.php.cn/) and installed with the Pear install Pecl_gen command.

Translator Note: Pecl_gen has been migrated to Codegen_pecl (http://www.php.cn/). This chapter deals with the version information of the code test using codegen_pecl: "PHP 1.1.3, Copyright (c) 2003-2006 Hartmut Holzgraefe", if you have a problem with your environment, refer to the translator's environment configuration in the translation sequence.

Once the installation is complete, it can run like Ext_skel, accept the same input parameters, produce roughly the same output, or, if a complete XML definition file is provided, produces a more robust and fully versioned version of the extension. Pecl_gen does not save you the time to write extended core functions; Instead, it provides an optional way to efficiently generate extended skeleton code.

Specfile.xml

The following is the simplest extension definition file:

<?xml version= "1.0" encoding= "Utf-8"? ><extension name= "Sample9" > <functions>  <function Name= "Sample9_hello_world" role= "public" >   <code><![ cdata[    php_printf ("Hello world!");] >   </code>  </function> </functions></extension>




Note: The translator uses the original in the first line of the missing question mark, resulting in the inability to use, plus on OK.

Run this file with the Pecl_gen command:

jdoe@devbox:/home/jdoe/cvs/php-src/ext/$ Pecl-gen Specfile.xml

An extension named Sample9 is generated and exposes a user-space function, Sample9_hello_world ().

About Extensions

In addition to the feature files you are already familiar with, Pecl_gen also produces a package.xml file which can be used for pear installation. This file can be useful if you plan to publish the package to the PECL library, or if you just want to deliver content using the Pear package system.

In summary, you can specify the elements of most package.xml files in the Pecl_gen specfile.xml.

<?xml version= "1.0" encoding= "UTF-8"? ><extension name= "Sample9" >    <summary>extension 9 Generated by pecl_gen</summary>    <description>another sample of PHP Extension writing</description >    <maintainers>        <maintainer>            <name>john D. bookreader</name>            < email>jdb@example.com</email>            <role>lead</role>        </maintainer>    </ maintainers>    <release>        <version>0.1</version>        <date>2006-01-01</ date>        <state>beta</state>        <notes>initial release</notes>    </release >    ...</extension>

When Pecl_gen creates an extension, this information is translated into the final package.xml file.

Depend on

As you can see in the 17th chapter, "Configuration and linking," dependencies are scanned for CONFIG.M4 and config.w32 files. Pecl_gen can use <deps> to define various types of dependencies to complete the scanning effort. By default, the dependencies that are listed under the <deps> tab are applied to both UNIX and Win32 builds, unless you explicitly specify a target with the Platform property

<?xml version= "1.0" encoding= "UTF-8"? ><extension name= "Sample9" >    ...    <deps platform= "Unix" >        <! UNIX specific dependencies >    </deps>    <deps platform= "Win32" >        <! Win32 specific dependencies >    </deps>    <deps platform= "All" >        <! Dependencies that apply to all platforms >    </deps>    ...</extension>

With

Typically, extensions use--enable-extname-style configuration options when configured. By adding one or more <with> tags to the <deps> block, not only is the configuration option modified to--with-extname, but also the header file needs to be scanned:

Deps platform= "Unix" >    <with defaults= "/usr:/usr/local:/opt" testfile= "Include/zlib/zlib.h"        >zlib Headers</with></deps>

Library

The required libraries are also listed under <deps>, using <lib> tags.

<deps platform= "All" >    <lib name= "Ssleay" platform= "Win32"/>    <lib name= "Crypto" platform= " Unix "/>    <lib name=" z "platform=" UNIX "function=" inflate "/></deps>

In the previous two examples, just check if the library exists; In the third example, the library is actually loaded and scanned to confirm that the inflate () function is defined.

Although the <deps> tag has actually named the target platform, the <lib> tag also has a platform property that overrides the platform setting of the <deps> tag. Use extreme caution when mixing them.

In addition, files that need to be included can also be appended with a list of # include directives in your code by using the

<deps>    

Test: The translator's environment

Constant

The user space constants are defined using one or more <constant> tags in the <constants> block. Each label requires a name and a Value property, and one must be an int, float, and one of the string's type properties.

    <constants>        <constant name= "Sample9_apino" type= "int" value= "20060101"/>        <constant name= " Sample9_version "type=" float "value=" 1.0 "/>        <constant name=" Sample9_author "type=" string "value=" John Doe " />    </constants>

Global variables

Thread-safe global variables are defined in almost the same way. The only difference is that the type parameter requires a C language prototype instead of a PHP user space description. Once defined and built, global variables can be accessed using the macro usage of Extname_g (Global_name) learned in chapter 12th, "Start, terminate, and some of these points". Here, the Value property represents the default value of the variable at the time the request is started. Note that this default value can only be specified as a simple scalar value in specfile.xml. Strings and other complex structures should be set manually in the Rinit phase.

    <globals>        <global name= "greeting" type= "char *"/>        <global name= "greeting_was_issued" type= " Zend_bool "value=" 1 "/>    </globals>

INI option

To bind thread-safe global variables to the php.ini setting, you need to use the <phpini> tag instead of <globa>. This tag requires two additional parameters: onupdate= "updatemethod" identification ini changes should be handled, access= "mode" and the 13th "INI settings" described in the same mode, "mode" value can be: all, user, Perdir, System.

    <globals>        <phpini name= "mysetting" type= "int" value= "the" onupdate= "Onupdatelong" access= "All"/>    </globals>

Function

You have seen the most basic function definition; However, the <function> tag actually supports two different types of functions in the specfile of Pecl_gen.

The two versions support the <summary> and <description> attributes you have already used at the <extension> level; Both types must have an <code> tag that contains the original C language code that will be put into your source code file.

role= "Public"

As you would expect, all functions defined as public roles will be wrapped appropriately in the Php_function () header and braces, corresponding to an entry in the Extended function table vector.

In addition to the tags supported by other functions, the public type allows you to specify a <proto> tag. The format of this tag should match the prototype shown in the PHP online manual, which will be parsed by the document generator.

role= "Internal"

The intrinsic functions involve 5 zend_module_entry functions: Minit, Mshutdown, Rinit, Rshutdown, MINFO. If you specify a name that is not one of these 5 will produce an error that Pecl-gen cannot handle.

    <functions>        <function role= "internal" name= "MINFO" >            <code>            <![ cdata[            Php_info_print_table_start ();            Php_info_print_table_header (2, "Column1", "Column2");            Php_info_print_table_end ();            ]] >            </code>        </function>    </functions>

Custom code

All other code that needs to exist in your extension can be included with the <code> tag. To place arbitrary code into your target file extname.c, use role= "code"; Or, use role= "header" to place the code in the target file php_extname.h. By default, the code is placed at the bottom of the code or header file unless the position= "top" property is specified.

    <code role= "header" position= "bottom" >    <![ cdata[    typedef struct _PHP_SAMPLE9_DATA {        long val;    } php_sample9_data;    ]] >    </code>    <code role= "code" position= "Top" >    <![ cdata[    static Php_sample9_data *php_sample9_data_ctor (Long value)    {        php_sample9_data *ret;        ret = emalloc (sizeof (Php_sample9_data));        Ret->val = value;        return ret;    }    ]] >    </code>

The name attribute of the <code> tag in the original is not supported in the translator's environment.

Summary

Using the tools discussed in this chapter, you can quickly develop PHP extensions and make your code less prone to bugs than handwriting. Now it's time to move on to embedding PHP in other projects. In the rest of the chapters, you'll use the PHP environment and the powerful PHP engine to add scripting to your existing projects, allowing it to provide your customers with more and more useful functionality.

The above is the content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • Related Article

    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.