Multiple extensions
PHP scripts can now use an extension with C++ classes with methods that provide supports for writing further PHP extensions. But how do other extensions get to use it?
The idea is to provide reusable code, such that binary size growth is restrained. The base extension is currently named "cppzpp", as this is where the C++ zpp namespace code is stored.
The external methods are all linked as the fully mangled names that C++ is known for. Mangling helps generate non-colliding names in the shared named function tables. All the other extensions, use the zpp headers only. There are a few inline functions in zpp.
Namespace "zpp" is the foundation classes, that manipulate the internal Zend PHP types. Namespace "wcc" has a large number of PHP classes implemented using the cppzpp extension. The extensions for the "Wcc" namespace extensions, contain PHP class implementations that work usefully together. A number of them depend on the wccz extension, for some web framework service classes.
The PHP-CPP C++ framework has its own shared library. This contains a lot of methods for storing and executing its own class initialize information.
Unresolved Symbols
Symbols in classes using the cppzpp extension, and a few Zpp namespace objects have symbol addresses initially "unresolved" for API and many standard PHP extensions. When PHP loads an extension, these various functions have not been yet assigned addresses. PHP tries to resolve them by lookups at the time of first call.
A quick look at the symbols list in the PHP-CPP library shows that it is full of standard library template methods, including container classes, that have been generated for the PHP-CPP extensions registration system. ZPP uses PHP provided script to create registration code, on per extension module basis, is compiled in with each C++ class as a C source file. PHP will complain if newly registered function function symbols are not present.
The registration function in the _arginfo.h file is called, and the returned zend_class_entry pointer, is then placed in the C++ static template class member. This is usually declared as base_obj_mgr<c++_class_name> member of the class header, assigning with the classEntry function. This will also call the virtual method init_class_fn(), in case any non-standard customisation of PHP object handler functions needs to be done. An example is the Config_Mgr class, a specialized base_obj_mgr<T> class, in wcc/config.h where xxx_dimension functions are set.
class Config : public base_d {
public:
template <typename T> class Config_Mgr : public base_obj_mgr<T>
{
protected:
typedef base_obj_mgr<T>::mydef basedef;
public:
virtual void init_class_fn()
{
// base class
basedef::init_class_fn();
#ifdef CONFIG_HANDLERS
zend_object_handlers& hand = basedef::handlers_;
hand.read_dimension = Config::read_dimension;
hand.write_dimension = Config::write_dimension;
hand.has_dimension = Config::has_dimension;
hand.unset_dimension = Config::unset_dimension;
#endif
}
}; // end Config_Mgr
static Config_Mgr<Config> omg;
//.......
PHP_MINIT_FUNCTION(Wcc_Config_reg)
{
auto ce = register_class_Wcc_Config();
Config::omg.classEntry(ce);
return SUCCESS;
}
When trying to build a library out of the zpp namespace, using a simple meson.build setup, a surprising number of PHP internal symbol names came up as unresolved at the link stage. There seemed no deciding if there is some way to "fix" this. A resort to a "script names" only approach will take bites out of efficiency. The idea of extension libraries is to provide a deep integration into the PHP binary. If the PHP load and link process cannot provide an address for a symbol, it will immediately post an error when access is attempted.
Another approach would be to identify all the PHP symbols used in zpp, and provide functions with duplicate code. This would have little guarantee of correctness and compatibility over a wide range, and goes against the primary need to provide deep integration.
So ZPP is coded in C++ by using the same approach as for C - coded extensions . It has made some occassional use of C++ containers. A static instance of a std::map used in the module setup of the ZPP class "Wcc\Response" . The str_intern class is used for string data, instead of std::string. The map is after setup treated as read-only. This corresponds to PHP script version of this class where class static array member is loaded with default data.
Simple PHP arrays with interned strings - zpp::str_intern, have been created during module init in the "Wcc\Route" class, to hold some constants of integer flags and HTML verb names. Destructors are not run for these, the arrays abandoned on module shutdown, and interned strings are likely already cleaned up by PHP and are taken to be inaccessible.
typedef std::map<int, str_intern> StatusCodeMap;
//...
void Response_init::init()
{
gStatusCodes = {
{100, "Continue"},
{101, "Switching Protocols"},
{102, "Processing"},
{103, "Early Hints"},
{200, "OK"}, //...
};
}
Listed below are most of the current classes and their distribution amoung the cppzpp dependent - derived extensions.
The classes were made to participate in a PHP web site framework. They were eventually collected into 5 seperate extensions, each one dependent on the wccz (first) extension for the functions defined in the zpp namespace.
The "inclusions" into a particular extension are governed each by a single C++ file, those filenames ending in _extn.cxx. Each of this includes the class source files and the headers from zpp namespace. Also is a "registration function" that calls all php module initialize code (C-Macro is PHP_MINIT) for the included classes, without which of course, PHP won't use them.
Except that wccz also includes the zpp source files. Class namespaces names are the same as the PHP script versions.
Inline C++ code?
Some, but not much inline C++ code has been used in the zpp namespace. This could be expanded. It might be interesting to try this for functions that use/call PHP symbols and addresses. Will this reduce unresolved symbols from an attempt to produce an external library?
extension usage
The derived extensions are split on what are hoped to be useful functional boundaries, as all extensions are generally designed around a particular specialization. This is here indicated by the last letter of the extension name. "Z" is required for any or all the others. "H" is for Html generation, "R" is for URL requests to call objects, "D" is for database functions and drivers, "M" is for more file format readers.
Binary sizes (k) are as compiled with gcc 14.2, for PHP 8.4.25 on debian. They are 7-8% larger for gcc 16.2, for PHP 8.5.10 on cachyos.
| extension | source | debian | cachyos |
|---|---|---|---|
| cppzpp | cppzpp_extn.cxx | 324 | 348 |
| wccz | zero_extn.cxx | 305 | 324 |
| wcch | html_extn.cxx | 418 | 444 |
| wccd | database_extn.cxx | 921 | 991 |
| wccr | routes_extn.cxx | 774 | 829 |
| wccm | more_extn.cxx | 273 | 300 |
Associative key collections.
Wcc\Config, implements storage by dynamic properties.
Wcc\Hmap, implements storage as an internal array.
PHP provides two kinds of access, via object properties, (->) and arrays ([$ix]). Object declared properties have controlled levels of access, public, protected and private. There is also restricted objects of dynamic property access, and specially named "magic methods". Objects can also simulate array access.
Arrays are more generic, with special array notation access, square brackets for string or integer keys. The Array datatype is subject to copy on write, making shareable write access only possible by giving access as reference.
PHP allows for variable or property names embedded in strings, but not array notation. Arrays of Objects of stdClass can optionally be returned in database query row results.
$s = "Hello $obj->property";
$s = "Hello $obj->{$name}";
PHP provides stdClass as an object class which has inbuilt dynamic properties.
PHP also has installed an object class with Array behaviours, which is the class ArrayObject, as part of "SPL" extension. This is usable with array notation, but is conveniently shareable as an object. A read access performance comparison of all of these will be presented later.
It seems useful to give ZPP the Config and Hmap example implementations of simple collection classes which support both property and array storage.
Classes for cache, cache package serialization.
Wcc\ICache, a cache front end for different cache backends. Wcc\ICacheData, a managed cache package handled by ICache, stored in a serialized form.
Cache support and implementation classes.
Wcc\CacheMgr - Manages multiple instances of Wcc\ICache from configuration by name, and provides some methods to read and cache files through a named cache. Uses expiry data stored in ICache. Wcc\Cache\SFile - A useful cache implementation for Session files. File storage prefixes an expiry time at beginning of file. Wcc\Cache\Noop - A cache implementation that stores nothing and returns nothing. Wcc\Cache\Libmemcached - Uses the Memcached PHP extension Wcc\Cache\Apcu - Uses the APCu PHP extension
Route coding and matching
Wcc\Route, Data for a route - URL, HTML verb, object-method target. Wcc\RouteSet, A serialized collection of Routes, both fixed and regular expression matched. Wcc\RouteMatch, A route, along with its decoded match arguments. Wcc\Target, Route target, a simple class with Object class name, method name, and module name. Wcc\Pair, A simple class to hold two properties. Wcc\RequestGlobals, Interface access to the SuperGlobals for _GET, _POST, _REQUEST, _SERVER. Uses Wcc\Hmap. Wcc\FileUpload, File details for uploads.
Manage view hierarchy and buffering to create HTML output.
This makes use of the Plates-like classes pattern after some shrinkage and mutilation towards simplication.
Wcc\IfLoadHtml, Interface with one function, getHtml(path,data):string Wcc\ViewOutput, Script implementation of IfLoadHtml, called by Plate class to extract data into the symbol table, then file load, and optionally buffer the output, and return the output.
Wcc\Plate, Manage name and path to template, exposed data, and named sections of html to be inserted. Calls the IfLoadHtml class obtained from Wcc\PlateEngine.
Wcc\PlateEngine, Holds named Wcc\Plates, and shared data, plus other functions that have most likely atrophied. A shared resource for Plate instances. Wcc\SimpleView, Render from a single template file.
Wcc\HtmlPlates, build and organize a view heirarchy, with data, and start rendering.
Wcc\HtmlGem, A monster html output class, many functions taking array arguments to output defined html segments. Wcc\IfFindLeaf , Interface to find first name-extension match in an ordered list of directories. Wcc\SearchList, Implementation of IfFindLeaf.
Wcc\MoneyFmt , A few functions to format numbers as currency.
Services, Dependency Injection
Wcc\Services, manages two lists, one of active functions/objects/data, another of deferred data, usually callable functions to create something active. If active service isn't found, the deferred list is searched for activation. Services manages a list of singleton classes by class name, "instances". Wcc\ServiceAccess. Other classes can inherit from this class to use magic method to access an active service, from a services instance, or the global services.
Class finder
Wcc\Finder, breaks down a class name, including namespace, to search for it amoung namespace indexed directory paths.
Class Loader
Wcc\Loader, uses Wcc\Finder, and tries to load the class by its expected found path.
ReflectCache
Wcc\ReflectCache Manages a cache of Reflection classes, and is a way of creating a class instance and calling its constructor, by class name, with or without arguments.
Assets
Wcc\Assets, Assets are javascript, css, inline styles, injected into HTML outout. Reads a configuation file, and has functions indexed asset selection, and various output generation to call from view templates.
Response generation
Wcc\Headers. Generate headers part of HTML response. Wcc\Response. Cache for PHP response generation and return.