SlideShare una empresa de Scribd logo
1 de 35
Descargar para leer sin conexión
Building Custom PHP
                                  Extensions



                         International PHP Conference 2012 Tbilisi, Georgia
Wednesday, December 12, 12
About me


    ‣ Ioseb Dzmanashvili
    ‣ Software Architect at AzRy LLC
    ‣ Teacher at Caucasus School of Technology
    ‣ V8 JavaScript engine contributor
    ‣ Author of uri_template PHP extension
    ‣ Author of Create-Form and Edit-Form link relation
           types (being RFCed now).

Wednesday, December 12, 12
This talk covers


    ‣ Setting up development environment
    ‣ Creating extension skeletons with automated tools
    ‣ Building and installing extensions
    ‣ Internals such as:
      ‣ Implementing and exposing C functions
      ‣ PHP parameter parsing
      ‣ Variables
Wednesday, December 12, 12
This talk doesn’t cover



    ‣ Thread safety topics
    ‣ Networking
    ‣ Object oriented programming
    ‣ Stream wrappers
    ‣ Memory
Wednesday, December 12, 12
My Experience



    ‣ URI Template Pecl extension
      ‣ https://github.com/ioseb/uri-template
    ‣ Available from Pecl channel
      ‣ http://pecl.php.net/package/uri_template
    ‣ Used by Guzzle HTTP client library and Drupal 8

Wednesday, December 12, 12
What it does?




  ‣ Implementation of RFC6570(URI Template)
  ‣ Resource Identifier - URI)
    100% compatibility with RFC3986 (Uniform


  ‣ 100% compatibility with RFC3629 (UTF-8)

Wednesday, December 12, 12
How to use it?

         // URI Template Data
         $data = array(
            "id"     => array("person","albums"),
            "token"  => "12345",
            "fields" => array("id", "name", "picture"),
         );

         // URI Template
         $template = "{/id*}{?fields,token}";

         // Transformation
         $result = uri_template($template, $data);

         //Produces:

         /person/albums?fields=id,name,picture&token=12345

Wednesday, December 12, 12
Why it is important?




         ‣ Possibility to achieve outstanding performance
         ‣ Possibility to learn PHP from inside out


Wednesday, December 12, 12
Preparing development
                                  environment




Wednesday, December 12, 12
Installing PHP dev package



         ‣ Linux(Debian)
                $ sudo apt-get install php5-dev

         ‣ Installing with Mac Ports on Mac OS X
                $ sudo port install php5-devel

         ‣ Use XAMPP developer package as an alternative
                for Mac OS X (painless solution)


Wednesday, December 12, 12
Creating extension


    ‣ Creating the configuration and build files
    ‣ Creating the header and basic C files, which includes:
      ‣ Creating initialization and destruction functions
      ‣ Including the correct headers
      ‣ Creating functions for use by PHP info tools
    ‣ Creating test files
Wednesday, December 12, 12
Tools for creating extensions




      ‣      Create extension manually
      ‣ Use ext_skel to generate extension
      ‣ Use pecl-gen to generate extension

Wednesday, December 12, 12
Generating extension
                                with pecl-gen



      ‣ Install codegen_pecl
             $ pear install codegen_pecl

      ‣ Create XML descriptor for extension
      ‣ Generate extension skeleton
             $ pecl-gen hello-world.xml


Wednesday, December 12, 12
XML descriptor (hello-world.xml)

                <?xml version="1.0" ?>
                <extension name="hello_world" version="0.1.0">
                   <summary>Yet another hello world PHP Extension</summary>
                   <description>
                        This is a sample "hello world" extension
                        for demonstration purposes only.
                   </description>
                   <maintainers>
                        <maintainer>
                              <user>ioseb</user>
                              <name>Ioseb Dzmanashvili</name>
                              <email>ioseb.dzmanashvili@gmail.com</email>
                              <role>lead</role>
                        </maintainer>
                   </maintainers>
                   <license>PHP</license>
                   <function name="hello_world" role="public">
                        <proto>void hello_world( string input )</proto>
                        <summary>Prints a hello world message</summary>
                        <code><![CDATA[ // C code goes here ]]></code>
                   </function>
                </extension>


Wednesday, December 12, 12
Generated extension structure
      $ tree hello_world
             !""     config.m4
             !""     config.w32
             !""     hello-world.xml
             !""     hello_world.c
             !""     manual
             #       !"" Makefile
             #       !"" file-entities.ent
             #       !"" functions.xml
             #       !"" hello-world
             #       #   !"" ...
             #       #   !"" functions
             #       #   #   $"" hello-world.xml
             #       #   !"" ini.xml
             #       #   $"" reference.xml
             #       $"" manual.xml.in
             !""     ...
             !""     php_hello_world.h
             $""     tests
                     $"" hello_world.phpt

Wednesday, December 12, 12
Generated hello_world() function

      PHP_FUNCTION(hello_world)
      {
        const char * input = NULL;
        int input_len = 0;

          if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC,
                    "s", &input, &input_len) == FAILURE) {
            return;
          }

          do {
            // C code goes here
          } while (0);
      }



Wednesday, December 12, 12
Modifying hello_world() function

  PHP_FUNCTION(hello_world)
  {
    const char * input = NULL;
    int input_len = 0;

       if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC,
                "s", &input, &input_len) == FAILURE) {
         return;
       }

       // our implementation
       php_printf("Hello world %s", input);
  }



Wednesday, December 12, 12
Installing extension

   ‣ Prepare build environment for PHP extension
           $ phpize

   ‣ Configure it
           $ ./configure

   ‣ Compile & Install
           $ make && sudo make install

   ‣ Enable extension
           $ php -d extension=hello_world.so -m
Wednesday, December 12, 12
Testing hello_world() function

   ‣ Create test.php file
   ‣ Write test code
           <?php

           echo hello_world("PHP Rocks");

          echo "n";


   ‣ Run script
           $ php test.php

   ‣ If you see following line everything is OK
           $ Hello world PHP Rocks
Wednesday, December 12, 12
Cleaning extension folder




   ‣ Get rid off compilation output
           $ make clean

   ‣ Get rid off build environment stuff
           $ phpize --clean




Wednesday, December 12, 12
PHP_FUNCTION




Wednesday, December 12, 12
PHP_FUNCTION expansion

                         PHP_FUNCTION(hello_world)
                         {
                           // rest of code removed for brevity
                         }



                                     expands to



void zif_hello_world(
  zval *return_value,                 // 1) variable to store return value
  char return_value_used,             // 2) if returned value was used
  zval *this_ptr TSRMLS_DC            // 3) pointer to object's internal state
)

Wednesday, December 12, 12
Exposing internal function

     function_entry hello_world_functions[] = {

         PHP_FE(hello_world, hello_world_arg_info)
         { NULL, NULL, NULL }

     };
                                    expands to



   function_entry hello_world_functions[] = {
      {"hello_world", zif_hello_world, hello_world_arg_info},
      { NULL, NULL, NULL }
   };

Wednesday, December 12, 12
Parsing Function Parameters


  PHP_FUNCTION(hello_world)
  {
    const char *input = NULL;            // variable to store parameter value
    int input_len = 0;                   // variable to store value length

      if (zend_parse_parameters(
            ZEND_NUM_ARGS() TSRMLS_CC,   //   1)   number of arguments
            "s",                         //   2)   format string
            &input,                      //   3)   address of *input variable
            &input_len                   //   4)   address of input_len variable
         ) == FAILURE) {
        return;                          // just return if something goes wrong
      }

      // actual implementation
      php_printf("Hello world %s", input);
  }




Wednesday, December 12, 12
Available Parameter Types

        Type Specifier                 C datatype                 PHP Type
        b                     zend_bool                  Boolean
        l                     long                       Integer
        d                     double                     Floating point
        s                     char*, int                 String
        r                     zval*                      Resource
        a                     zval*                      Array
        o                     zval*                      Object instance
        O                     zval*, zend_class_entry*   Object of a specified type

        z                     zval*                      Non-specific zval
        Z                     zval**                     Dereferenced zval
Wednesday, December 12, 12
Examples of parameter formats


                   // means that function expects:
                   //   a) required long parameter
                   //   b) required string parameter
                   //   c) optional long parameter
                   //   d) optional zval of non-specific type
                   zend_parse_parameters(..., "ls|lz", ...)

                   // menas that function expects:
                   //   a) required array parameter
                   //   b) required array parameter
                   //   c) required string parameter
                   //   d) optional long parameter
                   zend_parse_parameters(..., "aas|l", ...)



Wednesday, December 12, 12
Zval

                     _zval_struct {
                         /* Variable information */
                         zvalue_value value;     /* value              */
                         zend_uint refcount__gc;
                         zend_uchar type;        /* active type        */
                         zend_uchar is_ref__gc;
                     };

                     typedef union _zvalue_value   {
                         long lval;                /* long value       */
                         double dval;              /* double value     */
                         struct {
                             char *val;
                             int len;
                         } str;
                         HashTable *ht;            /* hash table value */
                         zend_object_value obj;
                     } zvalue_value;

                     typedef struct _zval_struct zval;

Wednesday, December 12, 12
Zval - Graphical Representation

                                     value

                                   long lval

                                  double dval

                             str char *val int len

                                 HashTable *ht
                             zend_object_value obj

                                 refcount__gc
                                     type
                                  is_ref__gc


Wednesday, December 12, 12
Internal Data Types

              Type Value                   Access Macros
       IS_NULL                 N/A
       IS_BOOL                 Z_BVAL_P(value)
       IS_LONG                 Z_LVAL_P(value)
       IS_DOUBLE               Z_DVAL_P(value)
       IS_STRING               Z_STRVAL_P(value), Z_STRLEN_P(value)
       IS_ARRAY                Z_ARRVAL_P(value)
       IS_OBJECT               Z_OBJVAL_P(value)
       IS_RESOURCE Z_RESVAL_P(value)
Wednesday, December 12, 12
Zval Reader Example
 void display_zval(zval *value)
 {
     switch(Z_TYPE_P(value)) {
         case IS_NULL:
             php_printf("NULL");                                 break;
         case IS_BOOL:
             php_printf("BOOL %d",     Z_BVAL_P(value) ? 1 : 0); break;
         case IS_LONG:
             php_printf("LONG %ld",    Z_LVAL_P(value));         break;
         case IS_DOUBLE:
             php_printf("DOUBLE %f",   Z_DVAL_P(value));         break;
         case IS_STRING:
             php_printf("STRING %s",   Z_STRVAL_P(value));       break;
         case IS_RESOURCE:
             php_printf("RES #%ld",    Z_RESVAL_P(value));       break;
         case IS_ARRAY:
             php_printf("ARRAY");                                break;
         case IS_OBJECT:
             php_printf("OBJECT");                               break;
     }
 }

Wednesday, December 12, 12
Returning Values

                             Type Value          Access Macros
       ZVAL_NULL(return_value)               RETVAL_NULL()

       ZVAL_BOOL(return_value)               RETVAL_BOOL(bval)

       ZVAL_TRUE(return_value)               RETVAL_TRUE

       ZVAL_FALSE(return_value)              RETVAL_FALSE

       ZVAL_LONG(return_value, lval)         RETVAL_LONG(lval)

       ZVAL_DOUBLE(return_value, dval)       RETVAL_DOUBLE(dval)

       ZVAL_STRING(return_value, str, dup)   RETVAL_STRING(str, dup)

       ZVAL_RESOURCE(return_value, rval)     RETVAL_RESOURCE(rval)

Wednesday, December 12, 12
Returning Values




                             PHP_FUNCTION(test_function)
                             {
                                 ZVAL_NULL(return_value)
                             }




Wednesday, December 12, 12
Books




Wednesday, December 12, 12
Questions?




Wednesday, December 12, 12
Thank You!




Wednesday, December 12, 12

Más contenido relacionado

La actualidad más candente

php-src の歩き方
php-src の歩き方php-src の歩き方
php-src の歩き方do_aki
 
2015年度GPGPU実践プログラミング 第1回 GPGPUの歴史と応用例
2015年度GPGPU実践プログラミング 第1回 GPGPUの歴史と応用例2015年度GPGPU実践プログラミング 第1回 GPGPUの歴史と応用例
2015年度GPGPU実践プログラミング 第1回 GPGPUの歴史と応用例智啓 出川
 
プログラミング言語のマスコットとか紹介
プログラミング言語のマスコットとか紹介プログラミング言語のマスコットとか紹介
プログラミング言語のマスコットとか紹介Takaaki Hirano
 
F#のコンピュテーション式
F#のコンピュテーション式F#のコンピュテーション式
F#のコンピュテーション式pocketberserker
 
攻略リニアカラー改訂版
攻略リニアカラー改訂版攻略リニアカラー改訂版
攻略リニアカラー改訂版小林 信行
 
PGI CUDA FortranとGPU最適化ライブラリの一連携法
PGI CUDA FortranとGPU最適化ライブラリの一連携法PGI CUDA FortranとGPU最適化ライブラリの一連携法
PGI CUDA FortranとGPU最適化ライブラリの一連携法智啓 出川
 
T119_5年間の試行錯誤で進化したMVPVMパターン
T119_5年間の試行錯誤で進化したMVPVMパターンT119_5年間の試行錯誤で進化したMVPVMパターン
T119_5年間の試行錯誤で進化したMVPVMパターン伸男 伊藤
 
「NVIDIA プロファイラを用いたPyTorch学習最適化手法のご紹介(修正版)」
「NVIDIA プロファイラを用いたPyTorch学習最適化手法のご紹介(修正版)」「NVIDIA プロファイラを用いたPyTorch学習最適化手法のご紹介(修正版)」
「NVIDIA プロファイラを用いたPyTorch学習最適化手法のご紹介(修正版)」ManaMurakami1
 
Fortranが拓く世界、VSCodeが架ける橋
Fortranが拓く世界、VSCodeが架ける橋Fortranが拓く世界、VSCodeが架ける橋
Fortranが拓く世界、VSCodeが架ける橋智啓 出川
 
화자인식 기술 및 관련 연구 소개
화자인식 기술 및 관련 연구 소개화자인식 기술 및 관련 연구 소개
화자인식 기술 및 관련 연구 소개NAVER Engineering
 
120901fp key
120901fp key120901fp key
120901fp keyksknac
 
TensorFlow XLAは、 中で何をやっているのか?
TensorFlow XLAは、 中で何をやっているのか?TensorFlow XLAは、 中で何をやっているのか?
TensorFlow XLAは、 中で何をやっているのか?Mr. Vengineer
 
F#によるFunctional Programming入門
F#によるFunctional Programming入門F#によるFunctional Programming入門
F#によるFunctional Programming入門bleis tift
 
C#や.NET Frameworkがやっていること
C#や.NET FrameworkがやっていることC#や.NET Frameworkがやっていること
C#や.NET Frameworkがやっていること信之 岩永
 
GPUをJavaで使う話(Java Casual Talks #1)
GPUをJavaで使う話(Java Casual Talks #1)GPUをJavaで使う話(Java Casual Talks #1)
GPUをJavaで使う話(Java Casual Talks #1)なおき きしだ
 
組み込みでこそC++を使う10の理由
組み込みでこそC++を使う10の理由組み込みでこそC++を使う10の理由
組み込みでこそC++を使う10の理由kikairoya
 
C#次世代非同期処理概観 - Task vs Reactive Extensions
C#次世代非同期処理概観 - Task vs Reactive ExtensionsC#次世代非同期処理概観 - Task vs Reactive Extensions
C#次世代非同期処理概観 - Task vs Reactive ExtensionsYoshifumi Kawai
 
LINEでビデオ通話してくれる妹を作ってみた
LINEでビデオ通話してくれる妹を作ってみたLINEでビデオ通話してくれる妹を作ってみた
LINEでビデオ通話してくれる妹を作ってみたYuji Ueki
 
MicroPythonのCモジュールを作ってみる
MicroPythonのCモジュールを作ってみるMicroPythonのCモジュールを作ってみる
MicroPythonのCモジュールを作ってみるKenta IDA
 

La actualidad más candente (20)

php-src の歩き方
php-src の歩き方php-src の歩き方
php-src の歩き方
 
2015年度GPGPU実践プログラミング 第1回 GPGPUの歴史と応用例
2015年度GPGPU実践プログラミング 第1回 GPGPUの歴史と応用例2015年度GPGPU実践プログラミング 第1回 GPGPUの歴史と応用例
2015年度GPGPU実践プログラミング 第1回 GPGPUの歴史と応用例
 
プログラミング言語のマスコットとか紹介
プログラミング言語のマスコットとか紹介プログラミング言語のマスコットとか紹介
プログラミング言語のマスコットとか紹介
 
F#のコンピュテーション式
F#のコンピュテーション式F#のコンピュテーション式
F#のコンピュテーション式
 
攻略リニアカラー改訂版
攻略リニアカラー改訂版攻略リニアカラー改訂版
攻略リニアカラー改訂版
 
PGI CUDA FortranとGPU最適化ライブラリの一連携法
PGI CUDA FortranとGPU最適化ライブラリの一連携法PGI CUDA FortranとGPU最適化ライブラリの一連携法
PGI CUDA FortranとGPU最適化ライブラリの一連携法
 
Lispでやる記号微分
Lispでやる記号微分Lispでやる記号微分
Lispでやる記号微分
 
T119_5年間の試行錯誤で進化したMVPVMパターン
T119_5年間の試行錯誤で進化したMVPVMパターンT119_5年間の試行錯誤で進化したMVPVMパターン
T119_5年間の試行錯誤で進化したMVPVMパターン
 
「NVIDIA プロファイラを用いたPyTorch学習最適化手法のご紹介(修正版)」
「NVIDIA プロファイラを用いたPyTorch学習最適化手法のご紹介(修正版)」「NVIDIA プロファイラを用いたPyTorch学習最適化手法のご紹介(修正版)」
「NVIDIA プロファイラを用いたPyTorch学習最適化手法のご紹介(修正版)」
 
Fortranが拓く世界、VSCodeが架ける橋
Fortranが拓く世界、VSCodeが架ける橋Fortranが拓く世界、VSCodeが架ける橋
Fortranが拓く世界、VSCodeが架ける橋
 
화자인식 기술 및 관련 연구 소개
화자인식 기술 및 관련 연구 소개화자인식 기술 및 관련 연구 소개
화자인식 기술 및 관련 연구 소개
 
120901fp key
120901fp key120901fp key
120901fp key
 
TensorFlow XLAは、 中で何をやっているのか?
TensorFlow XLAは、 中で何をやっているのか?TensorFlow XLAは、 中で何をやっているのか?
TensorFlow XLAは、 中で何をやっているのか?
 
F#によるFunctional Programming入門
F#によるFunctional Programming入門F#によるFunctional Programming入門
F#によるFunctional Programming入門
 
C#や.NET Frameworkがやっていること
C#や.NET FrameworkがやっていることC#や.NET Frameworkがやっていること
C#や.NET Frameworkがやっていること
 
GPUをJavaで使う話(Java Casual Talks #1)
GPUをJavaで使う話(Java Casual Talks #1)GPUをJavaで使う話(Java Casual Talks #1)
GPUをJavaで使う話(Java Casual Talks #1)
 
組み込みでこそC++を使う10の理由
組み込みでこそC++を使う10の理由組み込みでこそC++を使う10の理由
組み込みでこそC++を使う10の理由
 
C#次世代非同期処理概観 - Task vs Reactive Extensions
C#次世代非同期処理概観 - Task vs Reactive ExtensionsC#次世代非同期処理概観 - Task vs Reactive Extensions
C#次世代非同期処理概観 - Task vs Reactive Extensions
 
LINEでビデオ通話してくれる妹を作ってみた
LINEでビデオ通話してくれる妹を作ってみたLINEでビデオ通話してくれる妹を作ってみた
LINEでビデオ通話してくれる妹を作ってみた
 
MicroPythonのCモジュールを作ってみる
MicroPythonのCモジュールを作ってみるMicroPythonのCモジュールを作ってみる
MicroPythonのCモジュールを作ってみる
 

Destacado (7)

Java variables
Java variablesJava variables
Java variables
 
Php extensions workshop
Php extensions workshopPhp extensions workshop
Php extensions workshop
 
Phpcompilerinternals 090824022750-phpapp02
Phpcompilerinternals 090824022750-phpapp02Phpcompilerinternals 090824022750-phpapp02
Phpcompilerinternals 090824022750-phpapp02
 
How PHP works
How PHP works How PHP works
How PHP works
 
PHP, Under The Hood - DPC
PHP, Under The Hood - DPCPHP, Under The Hood - DPC
PHP, Under The Hood - DPC
 
Understanding PHP memory
Understanding PHP memoryUnderstanding PHP memory
Understanding PHP memory
 
How PHP Works ?
How PHP Works ?How PHP Works ?
How PHP Works ?
 

Similar a Building Custom PHP Extensions

Living With Legacy Code
Living With Legacy CodeLiving With Legacy Code
Living With Legacy CodeRowan Merewood
 
Drupaljam xl 2019 presentation multilingualism makes better programmers
Drupaljam xl 2019 presentation   multilingualism makes better programmersDrupaljam xl 2019 presentation   multilingualism makes better programmers
Drupaljam xl 2019 presentation multilingualism makes better programmersAlexander Varwijk
 
PHP: The easiest language to learn.
PHP: The easiest language to learn.PHP: The easiest language to learn.
PHP: The easiest language to learn.Binny V A
 
Symfony CMF - PHP Conference Brazil 2011
Symfony CMF - PHP Conference Brazil 2011Symfony CMF - PHP Conference Brazil 2011
Symfony CMF - PHP Conference Brazil 2011Jacopo Romei
 
PHP CLI: A Cinderella Story
PHP CLI: A Cinderella StoryPHP CLI: A Cinderella Story
PHP CLI: A Cinderella StoryMike Lively
 
Introducing PHP Data Objects
Introducing PHP Data ObjectsIntroducing PHP Data Objects
Introducing PHP Data Objectswebhostingguy
 
Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applicationschartjes
 
2018 05-11 the way we teach tech - phpday
2018 05-11 the way we teach tech - phpday2018 05-11 the way we teach tech - phpday
2018 05-11 the way we teach tech - phpdayJeroen van der Gulik
 
Multilingualism makes better programmers
Multilingualism makes better programmersMultilingualism makes better programmers
Multilingualism makes better programmersAlexander Varwijk
 
Objects, Testing, and Responsibility
Objects, Testing, and ResponsibilityObjects, Testing, and Responsibility
Objects, Testing, and Responsibilitymachuga
 
HackU PHP and Node.js
HackU PHP and Node.jsHackU PHP and Node.js
HackU PHP and Node.jssouridatta
 
Introducing PHP Latest Updates
Introducing PHP Latest UpdatesIntroducing PHP Latest Updates
Introducing PHP Latest UpdatesIftekhar Eather
 
Auto-loading of Drupal CCK Nodes
Auto-loading of Drupal CCK NodesAuto-loading of Drupal CCK Nodes
Auto-loading of Drupal CCK Nodesnihiliad
 
Dependency injection in Drupal 8
Dependency injection in Drupal 8Dependency injection in Drupal 8
Dependency injection in Drupal 8Alexei Gorobets
 
Supercharging WordPress Development in 2018
Supercharging WordPress Development in 2018Supercharging WordPress Development in 2018
Supercharging WordPress Development in 2018Adam Tomat
 

Similar a Building Custom PHP Extensions (20)

Fatc
FatcFatc
Fatc
 
Living With Legacy Code
Living With Legacy CodeLiving With Legacy Code
Living With Legacy Code
 
PHP7 Presentation
PHP7 PresentationPHP7 Presentation
PHP7 Presentation
 
Drupaljam xl 2019 presentation multilingualism makes better programmers
Drupaljam xl 2019 presentation   multilingualism makes better programmersDrupaljam xl 2019 presentation   multilingualism makes better programmers
Drupaljam xl 2019 presentation multilingualism makes better programmers
 
PHP: The easiest language to learn.
PHP: The easiest language to learn.PHP: The easiest language to learn.
PHP: The easiest language to learn.
 
Symfony CMF - PHP Conference Brazil 2011
Symfony CMF - PHP Conference Brazil 2011Symfony CMF - PHP Conference Brazil 2011
Symfony CMF - PHP Conference Brazil 2011
 
PHP CLI: A Cinderella Story
PHP CLI: A Cinderella StoryPHP CLI: A Cinderella Story
PHP CLI: A Cinderella Story
 
Introducing PHP Data Objects
Introducing PHP Data ObjectsIntroducing PHP Data Objects
Introducing PHP Data Objects
 
Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applications
 
2018 05-11 the way we teach tech - phpday
2018 05-11 the way we teach tech - phpday2018 05-11 the way we teach tech - phpday
2018 05-11 the way we teach tech - phpday
 
Having Fun with Play
Having Fun with PlayHaving Fun with Play
Having Fun with Play
 
Hardcore PHP
Hardcore PHPHardcore PHP
Hardcore PHP
 
Multilingualism makes better programmers
Multilingualism makes better programmersMultilingualism makes better programmers
Multilingualism makes better programmers
 
Objects, Testing, and Responsibility
Objects, Testing, and ResponsibilityObjects, Testing, and Responsibility
Objects, Testing, and Responsibility
 
HackU PHP and Node.js
HackU PHP and Node.jsHackU PHP and Node.js
HackU PHP and Node.js
 
Introducing PHP Latest Updates
Introducing PHP Latest UpdatesIntroducing PHP Latest Updates
Introducing PHP Latest Updates
 
Auto-loading of Drupal CCK Nodes
Auto-loading of Drupal CCK NodesAuto-loading of Drupal CCK Nodes
Auto-loading of Drupal CCK Nodes
 
Dependency injection in Drupal 8
Dependency injection in Drupal 8Dependency injection in Drupal 8
Dependency injection in Drupal 8
 
Supercharging WordPress Development in 2018
Supercharging WordPress Development in 2018Supercharging WordPress Development in 2018
Supercharging WordPress Development in 2018
 
ElePHPant7 - Introduction to PHP7
ElePHPant7 - Introduction to PHP7ElePHPant7 - Introduction to PHP7
ElePHPant7 - Introduction to PHP7
 

Último

Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 

Último (20)

Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 

Building Custom PHP Extensions

  • 1. Building Custom PHP Extensions International PHP Conference 2012 Tbilisi, Georgia Wednesday, December 12, 12
  • 2. About me ‣ Ioseb Dzmanashvili ‣ Software Architect at AzRy LLC ‣ Teacher at Caucasus School of Technology ‣ V8 JavaScript engine contributor ‣ Author of uri_template PHP extension ‣ Author of Create-Form and Edit-Form link relation types (being RFCed now). Wednesday, December 12, 12
  • 3. This talk covers ‣ Setting up development environment ‣ Creating extension skeletons with automated tools ‣ Building and installing extensions ‣ Internals such as: ‣ Implementing and exposing C functions ‣ PHP parameter parsing ‣ Variables Wednesday, December 12, 12
  • 4. This talk doesn’t cover ‣ Thread safety topics ‣ Networking ‣ Object oriented programming ‣ Stream wrappers ‣ Memory Wednesday, December 12, 12
  • 5. My Experience ‣ URI Template Pecl extension ‣ https://github.com/ioseb/uri-template ‣ Available from Pecl channel ‣ http://pecl.php.net/package/uri_template ‣ Used by Guzzle HTTP client library and Drupal 8 Wednesday, December 12, 12
  • 6. What it does? ‣ Implementation of RFC6570(URI Template) ‣ Resource Identifier - URI) 100% compatibility with RFC3986 (Uniform ‣ 100% compatibility with RFC3629 (UTF-8) Wednesday, December 12, 12
  • 7. How to use it? // URI Template Data $data = array( "id" => array("person","albums"), "token" => "12345", "fields" => array("id", "name", "picture"), ); // URI Template $template = "{/id*}{?fields,token}"; // Transformation $result = uri_template($template, $data); //Produces: /person/albums?fields=id,name,picture&token=12345 Wednesday, December 12, 12
  • 8. Why it is important? ‣ Possibility to achieve outstanding performance ‣ Possibility to learn PHP from inside out Wednesday, December 12, 12
  • 9. Preparing development environment Wednesday, December 12, 12
  • 10. Installing PHP dev package ‣ Linux(Debian) $ sudo apt-get install php5-dev ‣ Installing with Mac Ports on Mac OS X $ sudo port install php5-devel ‣ Use XAMPP developer package as an alternative for Mac OS X (painless solution) Wednesday, December 12, 12
  • 11. Creating extension ‣ Creating the configuration and build files ‣ Creating the header and basic C files, which includes: ‣ Creating initialization and destruction functions ‣ Including the correct headers ‣ Creating functions for use by PHP info tools ‣ Creating test files Wednesday, December 12, 12
  • 12. Tools for creating extensions ‣ Create extension manually ‣ Use ext_skel to generate extension ‣ Use pecl-gen to generate extension Wednesday, December 12, 12
  • 13. Generating extension with pecl-gen ‣ Install codegen_pecl $ pear install codegen_pecl ‣ Create XML descriptor for extension ‣ Generate extension skeleton $ pecl-gen hello-world.xml Wednesday, December 12, 12
  • 14. XML descriptor (hello-world.xml) <?xml version="1.0" ?> <extension name="hello_world" version="0.1.0"> <summary>Yet another hello world PHP Extension</summary> <description> This is a sample "hello world" extension for demonstration purposes only. </description> <maintainers> <maintainer> <user>ioseb</user> <name>Ioseb Dzmanashvili</name> <email>ioseb.dzmanashvili@gmail.com</email> <role>lead</role> </maintainer> </maintainers> <license>PHP</license> <function name="hello_world" role="public"> <proto>void hello_world( string input )</proto> <summary>Prints a hello world message</summary> <code><![CDATA[ // C code goes here ]]></code> </function> </extension> Wednesday, December 12, 12
  • 15. Generated extension structure $ tree hello_world !"" config.m4 !"" config.w32 !"" hello-world.xml !"" hello_world.c !"" manual #   !"" Makefile #   !"" file-entities.ent #   !"" functions.xml #   !"" hello-world #   #   !"" ... #   #   !"" functions #   #   #   $"" hello-world.xml #   #   !"" ini.xml #   #   $"" reference.xml #   $"" manual.xml.in !"" ... !"" php_hello_world.h $"" tests $"" hello_world.phpt Wednesday, December 12, 12
  • 16. Generated hello_world() function PHP_FUNCTION(hello_world) { const char * input = NULL; int input_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &input, &input_len) == FAILURE) { return; } do { // C code goes here } while (0); } Wednesday, December 12, 12
  • 17. Modifying hello_world() function PHP_FUNCTION(hello_world) { const char * input = NULL; int input_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &input, &input_len) == FAILURE) { return; } // our implementation php_printf("Hello world %s", input); } Wednesday, December 12, 12
  • 18. Installing extension ‣ Prepare build environment for PHP extension $ phpize ‣ Configure it $ ./configure ‣ Compile & Install $ make && sudo make install ‣ Enable extension $ php -d extension=hello_world.so -m Wednesday, December 12, 12
  • 19. Testing hello_world() function ‣ Create test.php file ‣ Write test code <?php echo hello_world("PHP Rocks"); echo "n"; ‣ Run script $ php test.php ‣ If you see following line everything is OK $ Hello world PHP Rocks Wednesday, December 12, 12
  • 20. Cleaning extension folder ‣ Get rid off compilation output $ make clean ‣ Get rid off build environment stuff $ phpize --clean Wednesday, December 12, 12
  • 22. PHP_FUNCTION expansion PHP_FUNCTION(hello_world) { // rest of code removed for brevity } expands to void zif_hello_world( zval *return_value, // 1) variable to store return value char return_value_used, // 2) if returned value was used zval *this_ptr TSRMLS_DC // 3) pointer to object's internal state ) Wednesday, December 12, 12
  • 23. Exposing internal function function_entry hello_world_functions[] = { PHP_FE(hello_world, hello_world_arg_info) { NULL, NULL, NULL } }; expands to function_entry hello_world_functions[] = { {"hello_world", zif_hello_world, hello_world_arg_info}, { NULL, NULL, NULL } }; Wednesday, December 12, 12
  • 24. Parsing Function Parameters PHP_FUNCTION(hello_world) { const char *input = NULL; // variable to store parameter value int input_len = 0; // variable to store value length if (zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, // 1) number of arguments "s", // 2) format string &input, // 3) address of *input variable &input_len // 4) address of input_len variable ) == FAILURE) { return; // just return if something goes wrong } // actual implementation php_printf("Hello world %s", input); } Wednesday, December 12, 12
  • 25. Available Parameter Types Type Specifier C datatype PHP Type b zend_bool Boolean l long Integer d double Floating point s char*, int String r zval* Resource a zval* Array o zval* Object instance O zval*, zend_class_entry* Object of a specified type z zval* Non-specific zval Z zval** Dereferenced zval Wednesday, December 12, 12
  • 26. Examples of parameter formats // means that function expects: // a) required long parameter // b) required string parameter // c) optional long parameter // d) optional zval of non-specific type zend_parse_parameters(..., "ls|lz", ...) // menas that function expects: // a) required array parameter // b) required array parameter // c) required string parameter // d) optional long parameter zend_parse_parameters(..., "aas|l", ...) Wednesday, December 12, 12
  • 27. Zval _zval_struct { /* Variable information */ zvalue_value value; /* value */ zend_uint refcount__gc; zend_uchar type; /* active type */ zend_uchar is_ref__gc; }; typedef union _zvalue_value { long lval; /* long value */ double dval; /* double value */ struct { char *val; int len; } str; HashTable *ht; /* hash table value */ zend_object_value obj; } zvalue_value; typedef struct _zval_struct zval; Wednesday, December 12, 12
  • 28. Zval - Graphical Representation value long lval double dval str char *val int len HashTable *ht zend_object_value obj refcount__gc type is_ref__gc Wednesday, December 12, 12
  • 29. Internal Data Types Type Value Access Macros IS_NULL N/A IS_BOOL Z_BVAL_P(value) IS_LONG Z_LVAL_P(value) IS_DOUBLE Z_DVAL_P(value) IS_STRING Z_STRVAL_P(value), Z_STRLEN_P(value) IS_ARRAY Z_ARRVAL_P(value) IS_OBJECT Z_OBJVAL_P(value) IS_RESOURCE Z_RESVAL_P(value) Wednesday, December 12, 12
  • 30. Zval Reader Example void display_zval(zval *value) { switch(Z_TYPE_P(value)) { case IS_NULL: php_printf("NULL"); break; case IS_BOOL: php_printf("BOOL %d", Z_BVAL_P(value) ? 1 : 0); break; case IS_LONG: php_printf("LONG %ld", Z_LVAL_P(value)); break; case IS_DOUBLE: php_printf("DOUBLE %f", Z_DVAL_P(value)); break; case IS_STRING: php_printf("STRING %s", Z_STRVAL_P(value)); break; case IS_RESOURCE: php_printf("RES #%ld", Z_RESVAL_P(value)); break; case IS_ARRAY: php_printf("ARRAY"); break; case IS_OBJECT: php_printf("OBJECT"); break; } } Wednesday, December 12, 12
  • 31. Returning Values Type Value Access Macros ZVAL_NULL(return_value) RETVAL_NULL() ZVAL_BOOL(return_value) RETVAL_BOOL(bval) ZVAL_TRUE(return_value) RETVAL_TRUE ZVAL_FALSE(return_value) RETVAL_FALSE ZVAL_LONG(return_value, lval) RETVAL_LONG(lval) ZVAL_DOUBLE(return_value, dval) RETVAL_DOUBLE(dval) ZVAL_STRING(return_value, str, dup) RETVAL_STRING(str, dup) ZVAL_RESOURCE(return_value, rval) RETVAL_RESOURCE(rval) Wednesday, December 12, 12
  • 32. Returning Values PHP_FUNCTION(test_function) { ZVAL_NULL(return_value) } Wednesday, December 12, 12