This book aims to describe a suite of C++ classes as being useful for creating PHP extensions. The foundation C++ classes for PHP type have the C++ namespace zpp. The code in this namespace manages low level access to PHP C structures for its data values and handles, and the base class and template for building PHP objects. for For want of a better name, this is labelled, the wccz module, "z" for zero, meaning first or foundation.

The ZPP classes wrap the C pointer-handles to commonly used Zend PHP data structures. There is also a wrapper class for a zval structure, and another to wrap a pointer value (zval*). Each of these classes has methods and operators to manage reference counting values, for common use cases, such as construtor, destructor and ownership transfer, that make it easier to write code. Using them, much direct use of Zend API C pointers and macros can be avoided.

Another four extension modules use this to implement C++ versions of PHP objects used in a web framework, implemented in PHP for Wcc and Wcd namespaces, and also have classes to read C++/C library code found that read few file text format types, such as xml, toml, and convert markdown.

In order to demonstrate techniques, and test common use cases via PHP internal classes coded extensions, a number of extension modules have been written that use and share the foundation wccz extension module.

These use example extension are class examples, which implement very closely, the methods and functions of same named classes written also as PHP script. This makes the script versions, and their matching extension components swappable to some extent, except where internal implementions depend on direct calls to their C++ objects and methods inside an extension.

The classes provided in the name-spaces "Wcc" and "Wcd", implement frequent used tasks in handling Web Server requests, and this was a big rolled up test case, requiring several support PHP script classes, with two versions synchonized, one with PHP scripts alone, and the extensions disabled, another using C++ implemented versions of the same, such that PHP interpreter never tries to load their script versions.

The web include working with Cache management, Routing, Page asset plugging, Modules, Html page template components, Request and Response objects, , Database Model and SQL Database interfaces. The extension versions have a small speed and memory resource advantage of always being "pre-loaded" for a PHP interpreter setup.

The PHP code, with its script only versions with extension module versions of their classes, should be called a "frankenstein". It also relies on a number of PHP script classes that are not implemented in C++. It does not then exactly follow any existing PHP frameworks. There are several such in open source land, all very good with their own framework integration, but not written with the thought of having C++ class replacements extension.

So with hack surgery of a simplified and possibly misunderstood framework ideas, Dr Frankenstein has put together misfitting and misused body parts, and where they seemed simple enough to implement, and have be modified enough to work together, and work with the same class API specified in "stub.php" files, to be implemented as an internal C++ class, all using the foundation class objects in the zpp namespace, until the entire thing seems understandable and seems to work without falling over. Now it is claimed that these tested examples, show proven ways to more easily build solid PHP extensions using the zpp namepace architecture.

PHP Script call backs for C++ extensions.

A few PHP script utility classes and methods, which are not implemented in the extensions, are necessary to provide assistance to some of these particular "extensionalized, frozen-compiled" classes. Some operations are easier to do in a PHP script function, but are less accessible from a C++ implementation module, for zend-compile technical reasons.

There is no HTML template system here, apart from PHP templates managed by a few classes very similar to an early version of "Plates". The PHP html views template organizing system, implemented here, is designed as modified, somewhat stripped down version of "Plates" An official website for faithful up-to-date versions this, resides at NATIVE PHP TEMPLATES. The code here is so modified that it would be waste of time to try to recall which version the modifications began with.

I don't keep track of recent developments, of things I start with, which I suppose is what happens coded ideas diverge, fork and evolve. This ZPP C++ shared version of plates has been stripped back, and only supports such usage that it has been tested with. This ZPP implementation here likely leaves out, merges or mangles a few features of its PHP source original. This statement is true of many of the classes in the ZPP-PHP dual suite. Only its PHP script code implementation, which need more documentation, and stub-files, and extension compatibility discipline the overall design

The "Plates" class employs a PHP script-only, "hand-off" class, as a call back interface, in order to handle script loads, and symbol table injection of values into them. This "ViewOutput" class need to be donated by script-land, and gives more customizability to the implementation our Plate class.

The Wcc web framework classes with optional extension support have their own auto-loader class, called as expected "Loader". Part of its functionality has been split into a "Finder" class, which looks for and locates PHP source files, by using a table of namespace prefixes which directs it to look into the sources namespace directory trees. This leaves the loader the task of loading the file, with the help of a file-loading closure call back, needed for a script call "require_once". There are ways to fully code the load functionality in C++, as a prescription of zend API calls is available but they would seem to offer more coding without much performance benefit.

Such callbacks also offer opportunity for Script code interventions and event recording. PHP scripts have their byte code is "opcached" and optimized well enough to make having extension implementations optimization a thing needing some justifications.

Scripts can benefit by using C/C++ Libraries and code in PHP extension classes

As so much of PHP functionality is implemented with builtin C extension modules, PHP has a sophisticated system of loading and calling them.

What generally makes many a PHP module extension useful is its interfacing with specialized existing libraries or C/C++ code for specific functions and optimization. There is a great diversity of extension modules. And with many builtin modules, they can be internally called from each other.

The ZPP examples present 3 examples of using C/C++ code libraries for optimized work.

An example presented is a Toml file reader class. PHP script based classes already exist, but their parsing and translation can be relatively slow.

A class to do effective Markdown parse to HTML here called "MarkToHtml" class, uses C code from the md4c project.

A JSON-like XML datafile format is described, and a class made to read it. The script or extenion variant XmlRead converrts its data to PHP arrays, which can include PHP classes with constructors that can work with no argument values. This gains significant execution efficiency using some slightly-modified C++ code from the TinyXML2 project, which for this usage improved on using PHP existing XMLReader class.

PHP request memory allocators

The original C/C++ code of these projects was open source, interesting, and had ready comprehensible designs and size. They where advantaged by being very modular, with a limited number of header and source code files. Their code was readible and had some obvious places of memory allocation. This offered places to modify to use the PHP request memory heap allocators, rather than the standard C/C++ memory allocation heap.

Defining the "arginfo" for PHP class registration

All PHP classes and functions in a PHP extension module have a registration function, which sets output the callable functions, classes and methods, and their argument and return types, to be integrated into the Zend interpreter. In all extensions now in common use, arginfo C code is generated from a [classname].stub.php file which lists them in almost the same PHP-script format as found in a full PHP script implementation. In the "skelaton" extension provided with the PHP-source distribution, their is a PHP-coded parser script, which generates the C-code for arginfo registeration, which only needs to be re-generated, included in source, and called from C++ code.

Deciding on the PHP classes, functions, methods interface is the first step in building a new extension. The ARGINFO registration code can also include declarations of class constants and properties, in the latest supported PHP syntax style.

All the PHP class APIs are contained in the stub folder, 33 classes have one stub file per class. Unfortunately the wcd classes have more than 10 interface/classes declared in one stub file, and several classes implemented in one .cpp file. Including the wcd namespace, there are at least 50 classes that are reasonably up to date and tested along with their PHP script versions. In the zpp namespace their are a dozen basic PHP data type classes to wrap sub-zval types, and a score of extra helpers, so that the classes implemented using these small class wrappers, rarely need to touch the unwrapped PHP API C-structures and various C- macros that generate inline code and zend API function calls.

Why so many classes? It was done to try to expand on various concepts, try to signifcantly reduce PHP script load time when used together,to provide refined classes to small moduler functionality, to have compatibility between script and extension versions, and also to try to get as much functionality written, integrated and tested to make the "zpp" namespace support classes, as complete and bug-proofed as possible. To facilate function calls using zpp wrapper objects, a number of familiar PHP functions were created in C/C++ to use optimized call access. For instance their is aa

ZPP - wrap Zend PHP Pointers

Writing a PHP extension in C or in C++ is a specialized programming task. The PHP api is extensive, its source code uses C programming language, with an extensive use of C- language macros. Which means time spent examining them "at depth" and the C structures they operate on, to confirm what code they cause to be compiled.

The C++ api here wraps several of the C API's for reference counted PHP values. The most common value types are Scalar values of Integers and Double floating point, boolean, stored entirely in a zval structure, and reference counted pointer values for variable length structures of Strings, Arrays and the organization of Php Objects that may use all of these.

Reference counted PHP entities are managed by a simple "smart pointer" C++ wrapper are the zend_object, HashTable, and zend_string, as well as a pointer to zval structure, that may require reference count management of contents.

Useful zpp classes

All of these are wrapped in a namespace "zpp". 'Z' stands for the zend engine, or 'zero', or whatever you like. Namespace names delineate the folder names of the source tree. Everything here assumes 64-bit OS address pointers. All classes whose names have _ptr or _rc endings are non-virtual. These have no virtual polymorphism, but use inheritance. With the exception of the zval_ptr, _rc inherits from the corresponding _ptr. Most of the C++ functions pass them as value-types. The _rc types always reference count updates, except in move operations. Mostly the _ptr are used as function arguments, to avoid uneccessary reference count changes. Functions generally return _rc types, to keep the retained PHP data structure "alive".

ZPP classes for PHP structures *_ptr, *_rc.

Not RC RC Wraps Zend type size(bytes)
obj_ptr obj_rc zend_object* 4
htab_ptr htab_rc HashTable* 4
str_ptr str_rc zend_string* 4
val_ptr zval* 4
_ val_rc zval 8

The top 3 classes here contain only a pointer to a PHP structure as a member. The suffix refers to the "behaviour". and each of these 3 in second column. Reference counted classes *_rc inherit all the access methods from the corresponding none reference counted class *_ptr in the first column. To this they add the reference counting of the enclosed pointer, and have additional methods that involve reference counting to maintain the life-time of enclosed PHP data. Using virtual methods would add a hidden virtual function table pointer to the class, which would remove an advantage of being the same instance size as the wrapped pointer type. Standard C++ constructor, destructor and operations take care of any requied refence count changes.

The 3 specialized value classes can all be constructed or assigned from a zval* pointer, or its wrapper class val_ptr, and can be safely declared as members of a C++ class, or as stack variables in function code.

The reference counted structures have in common the first part of a "zend_refcounted_h", a combination of 4-byte integer refcount, and 4-byte type_info.

Also reference counted is the class val_rc, which encloses and initializes a zval, and takes the size of two pointers. This common Zend structure is the PHP varient record with a typeid that can hold many things. The"zval" (_\zval_struct_), is a 16-byte structure, partitioned to hold data and type information. The first 8 byte value is the data which can be a 64-bit long or floating point, or a pointer to a bigger structure. The second 8 byte is divided to identify type of the data, plus various flags and space reserved for the Zend engine execution management.

Special Helper classes

Additional zpp classes exist to provide services for PHP externsion modules.

class Purpose
base_d Parent class for C++ classes that are embedded inside a zend_object
base_obj_mgr Parent class to manage PHP class instances with a base_d
datetime_obj An obj_rc for Datetime object
dt_interval An obj_rc for DateInterval object
fn_call Base class for calling PHP functions
fn_call_args Template class to call PHP functions with N parameters
for_key_value Iterate keys, values and index of HashTable*.
htab_rw Update, Append or delete HashTable*, after doing copy on write.
htab_walk Step iteration of keys and values of HashTable*
preg Methods to manipute strings by calling methods in the PHP extension for PCRE
str_buf Stream text to PHP API "zend_smart_str". Virtual inherits from str_out
str_intern zend_string made as "interned"
str_out Stream text to PHP output
str_perm zend_string allocated in permanent memory
str_temp zend_string for throwaway
state_init Setup structures for interned strings and constants during module initialization
timezone_obj An obj_rc for TimeZone object
zarg_rd Confirm and transfer PHP function arguments from zend_execute_data

Where to use ZPP classes

The reference counting (RC) class variants are for object member storage, and creating or deleting instances of data. They are used when reference counting operations are required. For instance, returning a newly created value from a function. The none-reference counting wrappers (NRC) are for passing the pointers around, where reference counting is unnecessary. This includes arguments passed to C++ functions and methods, as object data is considered to have secure ownership in the calling environment. All classes have a constructor method for a zval*. Only *_rc classes will increment a reference count.

The *_ptr classes are for methods and functions that do not require changing the reference count of their passed argument. If the same functions where available for the val_ptr, or val_rc, frequent type retrieval and test would be required to check for an appropriate PHP handle type. Instead they are used directly in available methods appropriate to their type.

These classes have been only tested on PHP 8.2 and above. They certainly won't be useful with PHP versions before 7

The non-reference *_ptr classes useful as parameters passed by functions. This makes them useful for passing arguments from zval* to methods with *_ptr type parameters. They are useful for returning access to C++ class objects members, where a reference counting change will not occur. In returning a referenced handle as result of a registered zend function, the return_value parameter is a pointer to a zval, wherein the rewturned value must be set, and a reference count increment is required, as expected by the Zend interpreter.

In cases where a new value is created and returned by a method or function, specific *_rc types can be returned, where this indicates that function stack values have been erased, to keep the reference count. If multiple types can be returned, a val_rc structure is returned. All of the *_rc types have C++ move operators declared as &&, and the compiler will likely perform Return Value Optimisation.

Setting the return_value

All of the wrapper classes have 2 available functions which need to be called to return a value back to a PHP script function or object method call, to the "return_value" zval pointer passed with PHP call.

// What Zend passes to all declared PHP C functions and methods.
#define INTERNAL\_FUNCTION\_PARAMETERS zend\_execute\_data *execute\_data, zval *return\_value

A function or method call from the PHP Zend Engine, is passed a pointer to a C structure "zend_execute_data". The number of parameters passed is accessed with C macro ZEND_CALL_NUM_ARGS(execute_data), and the zend_object* if a method call, is accessed by C macro ZEND_THIS which resolves to execute_data->This.

There is a large number of C API macros, and alternates to access and transfer parameters passed in the zend_execute_data structure to somewhere useful. A commonly used set of them start with ZEND_PARSE_PARAMETERS_START, or ZEND_PARSE_PARAMETERS_NONE. These test for parameter number and type compliance, and throw PHP defined exceptions when compliance fails.

In the more recent created classes of this code library I used a C++ class created with methods to replace the ZEND_PARSE_* macros.

These are the methods of zpp::zarg_rd class. Its methods take a reference to one of the above *_ptr reciever classes, and a zval* returned by the method need(size_t ix) or option(size_t ix) call, as an index into the execute_data array of zval parameters. It is a zero-based "slice" from the address of the zend_execute_data zval arguments.

As this class is new and different, it provides different error handling and error messages to ZEND_PARSE_* and C-macro helpers.

Returning values back to PHP

The second parameter of the INTERNAL_FUNCTION_PARAMETERS is the return_value, pointer to zval. By convention, each *_ptr class should use this method which will try to increment its reference count.

void copy\_zv(zval* ret) const;
/* For example, this does a reference counted copy to the zval*, even though obj\_ptr is otherwise not involved in reference counting. If it didn't do this, PHP will "dissappear" the object passed to it. The recieving zval takes reference counting responsibility, not the obj\_ptr.

This is most often used if the obj\_ptr class is in the scope of the ZEND\_FUNCTION body.
*/
void 
obj\_ptr::copy\_zv(zval* ret) const
{
    if (obj\_)
        ZVAL\_OBJ\_COPY(ret, obj\_); // set and bump reference count
    else
        ZVAL\_NULL(ret);
}

Instances of returned *_rc class, in ZEND_FUNCTION body, need to use their move_zv method and pass it the return_value pointer. This transfers the referenced value to the return_value, and sets its own valpointerue to a nullptr, which prevents the destructor performing a try decrement reference. This is a move operation, such that it makes no change in reference count of the copied pointer. The return_value keeps incremented reference count that belonged to _rc class.

void move_zv(zval* ret);
/* For example, this obj_rc already bumped the reference count on construction or assignment. It is therefor already counted. To ensure it does not decrement the reference count on object destruction,
after moving the pointer to the zval, its copy of the pointer is nulled. The zval is set with a macro that does not change the reference count. The ownership of the reference count is "moved".
Cannot call this with a const <_rc> & 
*/

void 
obj_rc::move_zv(zval* ret)
{
  if (obj_)
  {
    ZVAL_OBJ(ret, obj_); 
    //Z_TYPE_FLAGS_P(ret) = 0; // Not allowed to dereference
    obj_ = nullptr;// give up ownership privilege
  }
  else {
    ZVAL_NULL(ret);
  } 
}

A little bit of thought, and during development, some experimentation, is required to know whether to use copy_zv or move_zv, depending on the _rc or _ptr return type. An _rc object is going to decrement its reference counted value before it is zeroed out, if it is has not already been moved out by move_zv. If copy_zv is called from a _ptr class, it causes an increment reference count in the copy_zv, and there is no decrement count in the destructor. Calling copy_zv from a _rc class is okay also, excepting that both the increment on copy, and the decrement on destruct, are equivalent to just a move_zv call, except with more fuss.

Reading values in HashTables, and function parameters.

The val_ptr is useful in checking the value returned from array read methods of htab_ptr. All of the wrapped zend_hash read methods return a zval* which is either the address of its stored zval, or a nullptr value.

"Not Found" is represented by nullptr zval* result. Otherwise the returned zval* is a pointer to the values internal storage. All of the val_ptr class methods check for a nullptr.

As the PHP array can be indexed by strings, integers, and arbitrarily some of each, the most used method signatures for "get" methods returning a zval* have argument types of zend_long, aned_string*, str_ptr.

For convenience of having useful *_ptr access functions, obj_rc inherits from obj_ptr, htab_rc inherits from htab_ptr, and str_rc inherits from str_ptr. This inheritance does not imply that any of other kind of polymorphism is catered for.