Establish environment

Decide on extension name and directory location, this can be changed later. Make an extension skelaton. When the target PHP version or binary changes, maybe have to change the compile/install target, using command line in the source directory calls to phpize and ./configure. Also call these on any changes to config.m4.

Make a fresh folder extension start.

Perforce have a decent guide for building a PHP extension. Here is a link to Section 2, "Generating a PHP Extension Skeleton". This requires having installed a php-src distribution tarball. With latest distribution 8.4.12, have built a debug php version and environment.

In a linux home subdirectory ~/www I type the command. This Wcc\Pair class exists within within the wccr extension. It was inspired after looking at another non-standard PHP extension, the DS (Data Structures) extension, which has merits. A Pair of properties is almost a smallest data structure itself. Most likely small classes in an extension will not be used as a name of the extension. Here "wot" is name of the extension.

php php-8.4.12/ext/ext_skel.php --ext wot --dir .

The skeleton is for C coding. To have C++ do the work, small changes are required to config.m4. In config.m4, before the PHP_NEW_EXTENSION macro, add 4 lines, and rename the .c file as .cpp

  FLAGS="-fPIC"
  CXXFLAGS="$CXXFLAGS -Wall -O2 --std=c++23 -I./include"
  PHP_REQUIRE_CXX()
  AC_LANG([C++])

Run phpize, then ./configure, and make. Some warnings come up. Fix them and wrap includes *arginfo.h with an "extern C" wrap and a define guard for good measure. php_pair.h is the main include, with the extension version define, so move the other includes inside it from pair.cpp.

#ifndef PHP_Pair_H
# define PHP_Pair_H

extern "C" {
#include "php.h"
#include "ext/standard/info.h"
#include "pair_arginfo.h"
};

The skeleton build script has made a traditional "Hello World" function as test2. Clean this up. Copy the zpp folder to the new project, and recode it using zpp techniques. Include the zpp code. Delete the "For compatibility with older PHP and its define". Function test2 can be rewritten with ZPP classes and a zpp::state_init instance.

// Include all zpp
#include "zpp/base.cpp"
// For debugging
#include "zpp/show_zpp.cpp"

using namespace zpp;

class Global_init : public state_init {
public:
    str_intern world;

    void init() override {
        world = "World";
    }
};

Global_init Global_;

PHP_FUNCTION(test2)
{   
    zarg_rd args(execute_data);

    str_ptr name;
    str_rc  result;

    args.zstring(name, args.option(1));

    if (!args.throw_errors())
    {
        str_buf buf;

        if (!name.ok())
        {
            name = Global_.world;
        }
        buf << "Hello " << name;
        result = buf.zstr();
    }
    result.move_zv(return_value);
}

The skeleton needs a module init and shutdown functions, and request shutdown function for the state_init infrastructure.

    STANDARD_MODULE_HEADER,
   "Wot",					    /* Extension name */
    ext_functions,		        /* zend_function_entry */
  PHP_MINIT(wot),		    /* PHP_MINIT - Module initialization */
    PHP_MSHUTDOWN(wot),	    /* PHP_MSHUTDOWN - Module shutdown */
    PHP_RINIT(wot),			/* PHP_RINIT - Request initialization */
    PHP_RSHUTDOWN(wot),		/* PHP_RSHUTDOWN - Request shutdown */

And all the zpp::state_init static instances need to be told what to do.

PHP_MINIT_FUNCTION(wot)
{
#ifdef DEBUG_EXTRA
    dump_info::run_state_ = true;
#endif
    // Initialize static data instances
    zpp::state_init::init_all();
}

PHP_MSHUTDOWN_FUNCTION(wot)
{
    zpp::state_init::end_all();

#ifdef DEBUG_EXTRA
    dump_info::run_state_ = false;
#endif
    return SUCCESS;
}

PHP_RINIT_FUNCTION(wot)
{
#if defined(ZTS) && defined(COMPILE_DL_WCC)
    ZEND_TSRMLS_CACHE_UPDATE();
#endif
    zpp::state_init::init_request();
    return SUCCESS;
}

PHP_RSHUTDOWN_FUNCTION(wot)
{
    zpp::state_init::end_request();

#ifdef BASE_DEBUG
    zpp::mgr_link::report();
#endif
    return SUCCESS;
}

After all this need to do "make install", edit the php.ini for the test PHP environment for loading this extension. Run "php -m" to find the name of the new module in the module list.

Write and run a little test script. Oh wait, they are exist already in the tests folder. Run "php run-tests.php". Get result of "Tests passed : 3 (100.0%) (100.0%)".

The next stage is to remove the baby test functions, and put in the intended class and methods.

Make the class stubs

If a PHP class to be hardcoded exists, cut and paste the public methods declarations. Decide if any properties or class constants can be added.

The _arginfo.h generate script is very good, but has some restrictions. In the stub.files, the namespace declaration is required, but the parser has not yet managed to parse "use" statements yet. Full namespace path class names are necessary for anything not prefixed by the given namespace. Aim for seperate stub files, as each one becomes a separate _arginfo.h file. Properties, even read-only, and constants can be given simple values.

There is no neccessity have any declared public methods in the stub.php. Data types can be added in the C++ implementation class. Methods of access are important. Here a duplicate pair methods do the same thing. The property access is the most efficient way to read and write to objects of this class.

/**
 * @generate-class-entries
 * @generate-legacy-arginfo 80400
 * @undocumentable
 */
namespace Wcc;

final class Pair {

    public mixed $one;
    public mixed $two;

    public function __construct(mixed $first = null, mixed $second = null);

    public function first() : mixed {}

    public function second() : mixed {}

    public function key() : mixed {}

    public function value() : mixed {}

    public function test_calc() : mixed {}
};

Consider only public methods

It is presumed likely the equivalent of PHP private class functions will be implemented in C++ but will not accessible from a script. Similarly no protected methods have been implemented in the extension class examples. This saves on coding work. Where inheritance has been intended in the C++ object implementation, virtual function override has been used, although PHP class inheritance will surely work also by providing all the required zend method declarations.

In the stub file of a class, only public or protected methods or static functions need to be declared. The main concern of having a a __construct is to initialize all properties.

The stub arginfo.h generate C/C++ code which creates all of these declared properties when called from the generated class registration function. A __destruct function is useful for initial breaking of any reference cycles that may prevent easy garbage collection.

Write a build script

It gets boring to always type out make and arguments, so a build.sh script can dictate cleanups, rebuild and install command orders. To keep tidy a bit, create a stubs folder and move the stub.php and arginfo.h into it.

#!/bin/bash
# buildme script
make clean
make 

It seems that simple enough meson.build configurations exist to build and install PHP shared_modules.

PHP extension can global functions, not needed here

Once the function declarations test1() and test(2) are deleted, and replaced with the Run class declaration the "ext_functions" array declaration disappears from arginfo.h as well, and can be replaced with a nullptr, in the zend_module_entry declaration.

Meta instructions such "@generate-class-entries" have to be at the beginning, for the stub parser, before the namespace declaration, not after, or else only a very tiny amount of declaration code will be generated, without class entries or a registration function.

Create class files pair.h and pair.cpp

This class is going to be in namespace Wcc, for both PHP and C++, so make a folder wcc. Maybe use a different namespace name. Define guard their contents, in old-fashioned style. The extension main file will include the run.cpp, and test if defined for its inclusion. Its declaration is in run.h. Pair is also the name of the main extension file, so change it to php_pair.cpp, and update the config.m4 with this. Now this better matches the php_pair.h. Will have to run phpize and ./configure again.

Explain

The use of this class feels a little lost without its DS extension usage. It has been given a test_calc() method example in order to compare performance of method call to perform a calculation on the two properties.

Because the two values are stored in declared properties, the retrieval and test_calc functions have to retrieve the values using the property names, and the object / property method requires a zend_string* each time. This makes it more efficient to have the property zend_string already created and stored permanently as an "interned string". The PHP interpreter does this by hash table lookup for every string constant in all scripts it loads, and this takes care of having needless duplicates.

#ifndef WCC_PAIR_H
#define WCC_PAIR_H
//pair.h

#ifndef ZPP_BASE_H
#include "zpp/base.h"
#endif

namespace wcc {
using namespace zpp;

    
    class Pair : public base_d 
    {
    public:

        void construct(val_ptr p1, val_ptr p2);
        
        val_ptr first() const;

        val_ptr second() const;

        val_ptr key() const;

        val_ptr value() const;
        
        double test_calc() const 
        {
            long a, b;
            a = first().zlong();
            b = second().zlong();
            return (a + b) / double(a);
        }

    public:
    // for holding class meta data, will have to be defined as well as declared here
        static base_obj_mgr<Pair> omg;

    };
    
    /! static class interned strings
    class PairInit : public state_init {
    public:
        str_intern one;
        str_intern two;

        void init() override;
    };

    extern PairInit PairSI;

}; // namespace

#endif
#ifndef WCC_PAIR_CPP
#define WCC_PAIR_CPP
// The above is used to confirm singular inclusion of this file in "integrated" c++ inclusion units, that use extension .cxx

#ifndef WCC_PAIR_H
#include "pair.h"
#endif

#ifndef WCC_PAIR_ARGINFO
#define WCC_PAIR_ARGINFO
extern "C" {
    #include "stub/pair_arginfo.h"
};
#endif

namespace wcc {

    base_obj_mgr<Pair> Pair::omg;

    PairInit PairSI;

  void PairInit::init()
  {
            one = "one";
            two = "two";
    }
        
    void Pair::construct(val_ptr p1, val_ptr p2)
    {
         obj_ptr self(self_);

         self.property(PairSI.one, p1);
         self.property(PairSI.two, p2);
    }

    val_ptr 
    Pair::first() const
    {
        return obj_ptr(self_).property_ptr(PairSI.one);
    }

    val_ptr 
    Pair::second() const
    {
        return obj_ptr(self_).property_ptr(PairSI.two);
    }
}; // namespace wcc

using namespace wcc;

ZEND_METHOD(Wcc_Pair, __construct)
{
    zarg_rd args(execute_data);

    val_ptr a1 = args.option(0);
    val_ptr a2 = args.option(1);

    if (a1.is_nullptr())
    {
        a1 = val_rc::null_value_ptr();
    }
    if (a2.is_nullptr())
    {
        a2 = val_rc::null_value_ptr();
    }

    if (!args.throw_errors(__FUNCTION__))
    {
        Pair* cobj = zval_toc<Pair>(ZEND_THIS);

        cobj->construct(a1,a2);
    }
}

ZEND_METHOD(Wcc_Pair, first)
{
    ZEND_PARSE_PARAMETERS_NONE();

    Pair* cobj = zval_toc<Pair>(ZEND_THIS);
    val_ptr result = cobj->first();
    result.copy_zv(return_value);

}

ZEND_METHOD(Wcc_Pair, second)
{
    ZEND_PARSE_PARAMETERS_NONE();

    Pair* cobj = zval_toc<Pair>(ZEND_THIS);
    val_ptr result = cobj->second();
    result.copy_zv(return_value);
}

//Usually placed at the end, to easily find
PHP_MINIT_FUNCTION(wcc_pair_d)
{
    //WcR_ce = wcc_class_reg("Wc\\Route", class_Wcc_Route_methods);
    auto ce = register_class_Wcc_Pair();

    Pair::omg.classEntry(ce);

    STATE_INIT_ADD(PairSI)
    
    return SUCCESS;
}

ZEND_METHOD

This is a C-macro that generates a C-style function name. One must exist for each function declared in the _arginfo file, otherwise the PHP extension loader will drop out and report the missing function error.

Need the PHP_MINIT_FUNCTION to register class

This needs to be called from the main module code, during module initialization, or the Run class will not be available. If their are multiple class includes, the #ifdef make it easier to not include them.

The Pair::omg.classEntry function needs to be called with zend_class_entry pointer result. This is a virtual function, as such an opportunity for derived manager classes to override function names set in the structures of zend_object function handlers, or do other sophisticated object class tweaks during module initialization.

Make sure that Pair::omg has actually defined its instance of course, otherwise segfault happens.

The PHP_MINIT needs to be called within the general

// inside the PHP_MINIT_FUNCTION(wot) function
#ifdef WCC_RUN_CPP
    PHP_MINIT(wcc_pair_d)(INIT_FUNC_ARGS_PASSTHRU);
#endif