Development History
The ZPP wrapper classes started out as a means of hiding low level PHP structure manipulations. Macros are often used in C to reproduce C source code. C++ has those too, and uses those found in PHP C header files. C++ also has "C++ templates" for means of code generation, class inheritance, data hiding, and a number of autogenerated class methods good for Plain Old Data objects. There are three broad types of data in this ZPP.
The first is a pattern of wrapping PHP data pointers for the dynamic allocated and reference counted PHP strings, arrays and objects. They come in plain wrapped pointers, and their reference counted child classes. It took a number of revisions and rethinks, for this hacker to get a feel for the kind of C++ implemention that seemed to integrate best. These use plain inheritance, and no virtual functions, so the class size is the same as the wrapped pointer.
The second is for non-request, module initialized static data structures, which are initialized with PHP interned strings for requent reuse. This are in statically assigned memory linked together as lists, from the base class "zpp::state_init", internal to each extension, to get module and request initialize events. The zend implementation itself takes every opportunity to "intern" any static strings that make up every script, so many scripts together may refer to only one copy in memory of such "prepared" and shared strings. An extension C++ source with zpp::static_init in each source file, duplicates the memory storage a bit more, because the string has to exist in compiled code data segments, and how compiler/linkers can optimize duplications between source files is a shrouded mystery to me.
The third category is a number of function proxies, to make use of PHP cached function call information, for functions and object methods, which can be put in thread_local structures, or embedded directly in C++ parts of PHP objects, or even in the call stack of implementations.
The fourth category is the mechanism of holding PHP class registration information for C++ implementations of PHP objects. Such information includes PHP C function pointer tables, and PHP class implementation pointers. This is derived from zpp::base_d, and has a class tree that matches the implemented PHP class tree. It has a number templates, and virtual functions. Each C++ class object implementation, derives directly or indirectly from zpp::base_d. Each class should be given a template declared static member containing the PHP class information.
The fifth category of code, is the PHP neccesity to have "proxy functions", for its declared functions and methods, accessed through PHP scripts. The names of these and their PHP "arginfo" registration macros can be rely on the PHP scripts that generate their names from extension "stub.php" files. Inside these naming function/methods macros, are function specific PHP C macros, that check the zend_execute structure for the data types expected to be passed in the zval arguments array. They match data types to declarations, declare the place at which remaining arguments are "OPTIONAL".
In the process of trying to be a little more versatile, and push limites, I created a zpp::zarg_rd C++ class with methods to do a similar job to the PHP macros for the argument parsing process. I don't think anyone will be totally pleased with this part of the implementation. The zarg_rd class may set error information, which may call a PHP exception creation, instead of proceding with calling its C++ implementation method or function.
There is sixth category of code to handle, which is to detect exceptions and errors, but at the same time avoid using as much of the the C++ try - catch exceptions mechanism, which I have been brainwashed to think of as a sort of performance drag and complexity multiplier. Instead some functions use the ability of C++ to return almost POD structures with an errorcode and result type, which need to be checked and passed along. These are all zpp::error_return. Apon checking for "has_errors", it also checks to see if a zend_exception hook has been called since the last time an error_return was checked. Only before the exit of the PHP "proxy function", is a call made to log a PHP error / exception.
They are numerously defined in the PHP source code, and help to both to standardize, and hide how PHP data structures are manipulated. There is meaningful and consistent naming scheme to all of the zend-PHP macros, which has to be somehow maintained, but who knows all of that?
The ZPP class methods are generally not declared as inline, and so they provide an isolation wall from the PHP inner operations and C-style macros contained inside. With the referenced counting handle wrappers, much testing was required, with debug tracing, to ensure that reference counting was safely maintained with many class construtors, destructor, and all assignment and transfer operators required by development of the many class examples.
Before choosing to take this approach to making another PHP extension frameworks in C++, PHP-CPP is still the only big framework that has tackled this task. It has buried so much technical complexity by wrapping a zval structure firmly inside its PHP::Value class with lots of methods and operators, and built up extension support around this.
PHP-CPP has been around a long time, since at least PHP 5. It needed changes made after the big jump to PHP 7.0. These were very deep and broad on the inside, so a new version of PHP-CPP was created, and its PHP 5 versions archived. PHP-CPP has tracked many PHP version changes since, and the code is sprinkled with various compile time #ifdef PHP_VERSION macros in its source code.
The idea of C++ PHP extensions was sketchily proposed over a decade ago, and PHP-CPP was created to promote and provide this. I did some work trying out my extensions ideas using PHP-CPP, and didn't quire succeed in liking it.
I found that the PHP-CPP somewhat cumbersome, having to use its custom methods of building function call information. It also tended to lag behind various PHP new releases, which also kept other extension framework techniques lagging, such as zephir/phalcon. It builds a big shared library, and then again big extension binaries.
PHP-CPP also had issues with lagging behind each new PHP big version release. This is more of a testament to the road map pushes from PHP developers to keep PHP moving up with the ever moving compiled languages race.
Eventually I decided I had enough experience, more time (after retirement) and stubborness to do a "start again from scratch approach", using recent PHP releases since version 8.2. While doing this, I found it necessay to look again how PHP-CPP implements particular functionality and features, until I had looked far too many levels of Zend macro definitions in the many C-style macros found the PHP source code.
Early versions from scratch
I made a few extensions were patterned on initial versions of PHP script classs, and compiled in C. Then I made a prototype PHP data type handle wrapper, and found out, more by by trial and error which patterns of parameter usuage and C++ type modifiers, and operator calls seemed to have the least complications, and how they might the most customary usage I seemed to want the most.
Then there were problems organising the header dependencies, because zval, zval pointer, and hashtables have to work with everything. In writing more extension classes, more issues kept arising. Using a htab_rw class that does no reference counting itself, was partly from disatisfaction with the previous unhappy compromised object heirarchy, but miraculously working version, after thumping out memory reference count glitches.
Each growth and iteration of design was the result of experiencing where memory reference counts glitches had occurred from the previous effort, and finding out more of how the Zend type structures seemed to really work.
Useful debug trace classes, zend_string buffer classes, and function calling optimisation support were refined a number of times. All this rework flowed back to changes in all the zpp classes. Eventually I worked out what class names might be best used to distinguish the design features, and help me pick out visually the various C++ file names from the growing long list on my source code tree. Even this underwent a few revisions.
The web extension framework classes that make a great deal of use of ZPP are contained in the wcc and wcd namespace and source code folders. These demonstrate some interacting class implementations of reasonable complexity. The classes are better used together as a suite. classes such as Wcc\Services, Wcc\ReflectCache make use of static instances. The C++ class versions, are a subset of a framework, of PHP Script classes, using or inheriting the extension provided classes. The extension classes also tend to assume that their partner classes exist inside the extension, and functional related classes are grouped together in the same module. This leads to a few functional grouped module extensions as shared library code. All require the use the module containing the zpp classes.
Debug compiles of various evolving versions of PHP were compiled, from 8.2 , to 8.5, and run with the memory check tool valgrind to detect memory leaks, and track down segment faults. It is quite a long time now since I have had to make a change to the zpp class code because of this.
Any significant changes to zpp would require going through this process again. zpp itself has been rewritten, at least twice over, to reflect authors insights into what seemed to work better. The project initially started with ideas of how to make Wcc\Route and Wcc\RouteSet classes, written as a much smaller C-code style extension, and versions of these had also been done with Zephir and PHP-CPP.
Parts of the design of the these script classes were adapted from existing Phalcon framework that used the intermediate Zephir langange to be generated and compiled as C.
PHP Script classes helpers to work with.
The framework classes require a few small helper classes that do some tasks that would be hard to do, or have no benefit from implementation directly in the zpp C++ code base.
Two examples in mind, is a class loader function/class, and related to this is a class to load view templates. It is possible to have such in the C++ extension, but it duplicates what PHP engine does very well, and it helps development to have this available in a scripted XDebug environment.
A Performance comparison to PHP-CPP
How well does ZPP , or the hybrid verison, PHP-ZPP compare to PHP-CPP?
Of course a reader can expect bias and some waffle here, along with some selective statistics, to get a "rough idea", as all statistics are selected by some means or other. Comparisons have been compiled and compared on the same machine. And of course PHP interpreter must also be included, as the extension classes where intentionally co-developed in PHP script.
The most frequently used test during development, is the class Wcc\XmlRead is an extension class made to read a customized but flexible XML file format, that has a similar data nesting description style aims as JSON.
XmlRead returns tree of particular XML formatted data as a combination of PHP array and Objects with dynamic public properties. Supported is the ubiquitous "Config" objects that every framework has of some kind, that uses properties, and of course PHP arrays cannot be left out either.
Individual elements in xml are for PHP types, and use a "k" attribute if a keyed array value. A <tb> tag represents a keyed array, and <a> represents a packed array or from-zero indexed list.
The file format is read and returned a PHP array. The Xml format can include specified xml tags to instantiate a PHP class, and includes common PHP datatypes, arrays, and keyed tables, using defined tags and attributes in typical XML style.
PHP already has optimized JSON functions, and the most versitile and fast data file format is PHP code. XML is a much spruiked as a portable format. Here the format is used to test the ZPP classes and its extension C++ helpers. It was a learning example I was familiar with, had a PHP script version of, and so it lent itself to trials.
The code is implemented in 3 environments. All use the PHP extension class XMLReader, to process the input file, and so this tests the efficiency of function calls to this extension class and getting its object properties, for each Xml element. The versions are 1) PHP Script, 2) PHP-CPP compiled class, and 3) a similar class implemented with the ZPP classes.
Each is compared using the same input test file over many iterations for an average time. The PHP timer function microtime measures time past for each iteration. Ten iterations are done as a "warm up", and then 200 iterations averaged, to get a value for microseconds per iteration.
The results show the average time in ms per iteration, and the ratio of this to the PHP script version, which to itself is 1.0.
The code for PHP-CPP and the zpp versions make use of the PHP extension XMLReader class object. This progresses through each XML node, and read its changing properties. Working through this is a little bit slow.
The zpp version uses a cached instances of fn_call class, which improves PHP function call time, and overall is about 10% faster than the reference PHP script class implementation.
| Version | ms / iteration | relative |
|---|---|---|
| PHP script class | 1,992 | 1.0 |
| PHP-CPP version | 4,355 | 2.8 |
| ZPP version | 1,788 | 0.9 |
These figures of msec per iteration, are pretty slow, done on a more than 10 years old machine, with an older PHP version.
A recent similar comparison test at the time of revising this chapter, show a different picture, with PHP 8.4, with an middling AMD Ryzen 5. The PHP script has had only minor changes, The PHP-ZPP version is an experimental custom version of PHP-CPP rewritten and stripped somewhat by using ZPP classes. The ZPP version no long uses XMLReader, and uses embedded TinyXml2 which is directly embedded, to implement the same class.
| Version | msec / iteration | relative |
|---|---|---|
| PHP script class | 505 | 1.0 |
| Custom PHP-CPP with ZPP | 308 | 0.61 |
| ZPP with TinyXml2 | 96 | 0.19 |
PHP-CPP adds not much for working directly with zend_string type. It assumes all code will use std::string. PHP-CPP has a fledgling zstring class which creates a zend_string assigned to "permanent memory".
PHP-CPP makes function and method calls with their names passed to PHP's call_user_function. The ZPP based classes practice PHP call caching using zpp::fn_call helpers.
The PHP-ZPP project was created by utilizing ZPP classes in PHP-CPP, and this speeds up calls to XMLReader methods, enough to improve on PHP script optimisation.
Later on another version of this extension class bypassed XMLReader class by using the XML parser from the C++ coded TinyXml2 project.