PHP scripts and extensions.

PHP is a computer language, which is compiled to byte-code and "interpreted", which means it is a "virtual machine". Its script facilities have many callable functions and object methods defined by its C-API extensions, and so run as native machine code. Recent PHP versions include just-in-time compilation to compile and optimize frequently used byte code.

PHP many compiled extensions supply core functionality across many domains, and are compiled its standard distribution. Many third party extensions exist, that can supply added specialized functions as needed. There is recently a facility for creating ad hoc calls to the ABI of third party system libraries. There are currently about 80 extensions, distributed with the core source code, an estimation based on a count of the number of sub-folders in its "ext" folder.

Extensions are shared libraries of code, which are loaded and called for registration of objects and functions metadata. Extensions use the common shared library format (*.so in linux, *.dll for Microsoft), that share their public data and functions with each other and the process that loads them. PHP source and most of its core extensions are written in C, supposedly a low level programming language. Generally, such extensions use a large numbers of C-macros that are exported in PHP headers, which are compiled to bring in a lot of in-lined code, as well as calls to exported structure types and functions from other extensions and zend API.

Most PHP extensions are written in C-programming language. Using C++ inherits all of its benefits.

Zephir - a half-way compileable script.

Zephir is script language for a compiler that translates to compilable C source code to build a PHP extensions. It was created as script that maps PHP features to enable the features of phalcon PHP web framework extension, such that all the extension classes constitute the web framwork. Zephir script works as a specialized higher level language, for PHP extensions, to avoid the pain of editing and debugging large amounts raw C source code. The zephir script first stage compiler is also implemented as an extension in itself. For a large framework of classes to manage the Zephir to generated extension C code has been a competing option. Building PHP extensions is easy with Zephir

The end results are efficient, when working within its capabilities. Nothing that requires working with and manipulating of the underlying zend structures does very much better than optimized or just-in-time compiled zend byte-code interpreter itself, on average. As a compiled extension, it skips these compile-optimization first load steps and has a library, only needs to be loaded once. The Zephir build process is a little clunky, and the specialised script has limits of expressivity, that lag upgrades to PHP versions. The generated C code is hard to read. The Zephir source script types available can be encourage to use native C types inside functions where possible. I have adapted some of the zephir code framework, to turn them ordinary PHP script classes, that can also be coded into ZPP extension classes. Zephir also has complex two stage build process, requiring a zephir-compile php extension installed in order to tranlate the zephir code an intermediate form, before analysis and translation to generate and compile C code. Its an ongoing process as PHP also progresses, now I see it is at version 19.0. Again its another specialized language, but its at least at a higher level than custom layers of C-macros. I can't possibly work on zephir versions of extensions while trying to develop the capabilities and classes using ZPP, so I have left zephir behind.

PHP-CPP

PHP-CPP is a C++ class framework to build a shared library and PHP API extension classes and functions. Therefore C++ can be used to hide PHP low level complexity. Can the PHP-CPP framework be improved upon? Both the Zephir and PHP-CPP process produce large binaries. PHP-CPP uses specialized C++ structures to construct class method definitions, and this isn't quite as flexable as the currrent PHP C-code methods, since PHP scripts can now generate class definition and registration C--code for class API definitions from class script "stub" files. In another sense PHP-CPP is very high-level C++, with heavy use of the single Value class that wraps all lower level PHP data types. Currently the source code is stuck at the C++11 standard, although this can be fixed, by merging some ZPP integration

PHP binary API

PHP script functions and class methods are shared C functions coded in extensions, with their names and arguments registered by each extension module so that they are callable from the PHP interpreter engine.

The full source of every published PHP version ever is downloadable as the "php-src" git repository on github. Types are in the zend_types.h file in the Zend folder. zend_types.h

Get the best code execution level

The aim of writing an extension is to provide efficient functions and object methods that improve on the the best script byte code interpreter, or JIT compiler, and hard-code into compiled native binary executable code. Extensions can link to other system libraries that support C-APIs and provide access to new and extended functionality.

Inside the zval

Data is exchanged between interpreted and compiled code through exchanges of the PHP data types managed by zval structures. Nowadays a zval has a 64-bit value storage area, and an adjoining 64 bits of type of value identity and management data, with some of these management bits not yet claimed. In C language terminology the value space is a union type that can store anything that size or less, and data management is so the interpreter machine can store, fetch and appropriately handle the meaning of those value bits.

A closer look reveals that some of the underlying assignable datatypes that require more memory than the typed 64-bit value storage space of the zval, are pointers to defined type structures that need extra dynamic memory, such as zend_object, hashtable (zarray), zend_string. These pointers are passed alone to many functions in their own rights, they have their own suite of C - management functions, as function arguments and return values. This is lower level of management than the zval. If C++ is to exploit more detailed possibilities in PHP data types, then it needs to handle common PHP datatypes by themselves, as well as their interactions with zval. This is how extension functions and object methods work in general.

The PHP array/hashtable type, as all the zval management code, can store every kind of mix different type-labelled thing, in its managed zval. This is what gives PHP its script interpreter kind of any-typed versatility.

PHP provides C-Macros to check function arguments and further checked to extract some of the reference counted handle types. zend_string*, zend_object*, and HashTable* can already be directly extracted from zend_execute_data, by using ZEND_PARSE_PARAMETERS_START macro, found in zend_API.h.

Also found in this _zend_API.h header, are C structures to assist calling other PHP functions and class methods, these are _zend_fcall_info_, and _zend_fcall_info_cache_. ZPP makes use of these in its zpp::fn_call and zpp::fun_call_args structure declarations. Repeated use of the same call will speed the call using the cached reusable call data.

Inside the method call

Getting the L-values

Check out the zval structure arguments pointed to, See if we the zval management data has the right particular data types required by the operation to be performed. Extract the value(s) from the zval. Cast them to the expected pointer type, or scaler value.

Do the work

Do some specific work with code lines, loops, recursions and calls to other functions that read, calculate to create create new pieces of data, pointer types and scaler values as required. Change storage states with new data value results if any, into private structures of objects and arrays. Storage may be raw pointer types, or just reset into zval structures with appropriate value and management data. Delete the no longer required values.

Return a value

Set a special zval structure pointer from the caller to return a value in , with its management data. Return back to the caller. Not setting this value returns a value of Null.

Except if something goes wrong.

If something wrong is detected in all of this, set up exception / error report information and let the interpreter exception machinery pick this up the calling stack.

Who cleans up the mess afterwards?

All of this is pretty general, and so its nice to have simple classes with methods that do housekeeping code, and clean up after themselves, with minimum fuss. C++ has defined many class method facilities that when coded well, work with the compiler for optimized purposes, which aims to manage the house-keeping complexity behind the scences, out of the high level code.

Usefulness of extensions

Apart from calls to and from the PHP API, the idea is that extension C/C++ code works with raw data structures of numbers, strings, and data storage, for which such compiled languages are designed. PHP strings and array storage is useful to use directly.

Array storage requires zval fetch and store, for the HashTable* API, and this is excellent for many purposes, as these are the all-purpose data store used in PHP scripts.

Object API and method calls is used extensively for services coordination between objects. Having underlying C++ objects in an extension, allows fast inter-object classes coordination to bypass the script engine. When extension objects provide really useful services, exposing classes and functions joins the community of useful extensions in PHP script space.

Extension source code

Many standard extension implementations distributed with PHP. This make PHP a rich, productive and efficient scripting environment. Inside, there are many zend API calls, many thousands of lines of source code. Deciphering it all can take a long time, even for a C-language expert.

Starting with C

There are beginner guides online, all assume that naturally PHP extensions are coded in C. There is some scattered information about for building a PHP extension using C++. I made use of the Zend - Perforce online guide as a beginner to building my first version of a PHP extensions in C, so I have been a while on that long journey. The current online link is Writing PHP Extensions,

C++ wraps C as a superset

C++ knows C code, and can directly use the PHP C header files, and C++ will directly use the PHP source of structures. Generally the C-macros, functions and macro constructions in headers must be imported with the wrapping of extern "C". It therefore should be easy. C++ is a superset of C, so no problems? Right?

What follows will be what I learned as I coded a C++ extension for PHP to make useful classes for an efficient web-site framework. This is the ZPP and PHP Classes framework. Its unfinished of course, because the PHP and ZPP versions are meant to be interchangeable, even has more PHP classes still be hard coded into using ZPP.

Merely "hard-coding" a framework as a shared library, does not by itself ensure execution efficiency. Only if the "method work" being done is already well suited to the overall purpose, is necessary, is done with an efficient algorithm, and integrates, but not duplicates work done by other methods.

Web Classes C++ extension

This Wcc framework objects also exists as pure PHP-script, which is backup for the same functionality, if the extension is not loaded. Wcc is currently an anacronym for "Web Classes C++ extension".

The framework can be used as PHP script code, no C++ extension necessary. The classes in PHP-script form have the same name and methods, and work the same, although some overall execution time increase can be measured.

The Wcc classes structure and design are I hope, reasonably efficient in terms of using the PHP environment, and achieving performance and usability goals. The script versions of the classes will not be loaded by the PHP engine, when the classes are already loaded as the C++ extension. Wcc is the namespace, and the extension name.

Match PHP script and extension API

When an extension version of any PHP class is already loaded, obviously the PHP engine does not call registered loaders to look for a script version of classes it already has. A forced script load of an extension class will produce an error saying the class is already loaded. Its good to have the script versions as backup, if for some reason, a new version of the ZPP based extension has a flaw.

  • The documentation of the ZPP class API should be easier using PHP documentation tools that read the PHP script versions. At the moment this class documentation is typically lacking.

  • The Wcc extension objects API replicates a subset of the classes of the script version. The hard-coded ZPP extensions should have the same class names and method names, and function call arguments, that is, identical to the .stub.php files used in the extension compile.

Extension library should require minimal setup code, that ensures script and ZPP versions are compatible. When using a PHP extension, the script versions of the same class are not loaded. Because of the mixin of callbacks, the ZPP extension, requires that the PHP script code is present for those class and callbacks that provide needed support. ZPP classes may be extended by script classes.

If a ZPP class function provides a call back, or expects a method that it calls can be overridden by script class extend, then the C++ code has to call it via the PHP call mechanism, rather than a C++ virtual or method call. Otherwise the override won't happen.

Wcc\Loader implementation, load script callback

When hard coded inside a compile extension, classes are marked as "internal classes" by the Zend Engine. These are privileged classes regarding the Zend API, but there is some API functionality, that is not available, or is more difficult for an "internal" class. Examples of necessary but simple helper classes written as PHP script in the Wcc suite are the Wcc\Loader class and the Wcc\ViewOuput class. Loader as compiled class requires a script callback function to do the loading. Its set by a call to setExtLoader, with the value of function to call, that takes the argument of string as the file path to load by calling require_once. The script function assigned to a zval, must return anything returned by require_once, as returned from the loaded script file.

PHP-CPP provides a reasonable looking Script class, which caches a returned zend_op_array after calling zend_compile_xx function. Its method execute() can run the op-codes multiple times if necessary and gives a return value. The opcodes can be returned from the ZEND_API method zend_compile_string. So ZPP could do loads without a callback. However the call back can be very useful to have for load interceptions during script debugging.

The script-only version of Loader could call require_once itself, but for compatibility and matching simulation reasons, also uses the simple callback function. The Script class is compiled into the PHP-ZPP merged library described later. I havn't imagined a need for this code, it might subvert various PHP caching optimisations. Usually "require_once" states an intention to let the PHP application look after the script execution codes.

Performance matching

  • The difference between script-only and using the extension is performance, as measured by memory usage, and execution speed, stability and systems code sharing. More built in classes can reduce PHP execution load time, presuming they are always needed. The PHP interpreter work includes dynamic reading script files, conversion into byte code, and then execution. All this takes up extra memory and processing time. Various cache mechanisms can be used to reduce script reading time and compile, execution memory overhead.

The Wcc extension classes are for web site processing tasks, such as module,route, and template management, seems to have a speed up of 60-70% of the time compared to script versions, on a general web request. That is including all the cache managment, repeated calls to allow for systems caching and just-in time compilation of the FPM-daemon which can optimize on repeated code

  • The Wcc objects are coded and compiled in a typical, PHP generated, C-extension development environment that is a modified C extension development environment. The C arginfo interfaces, used to register classes and functions into PHP, are generated from the same PHP stubs function - class - method files. Only the C++ compiler is used instead of a C compiler. This is specified by a editing a few lines in the "config.m4" that is used to auto generate "configure" script and a Makefile.

  • The C++ extension, and the PHP script classes version of them were co-evolved, to ensure compatibility. Opportunities for improvement needed to be managed in both.

I had designed and tested these classes already in PHP, and I wanted to find out how much performance might improve when the PHP classes are implemented as "internal classes" using C++.

There are many popular PHP script web frameworks out there. All of them keep improving and hopefully display some conversion with current standards and best practices. However there is a contrary tendency with software development to building larger code bases with increasing complexity and obscure APIs.

There are many operations and computing resources not efficiently implementable at the level of PHP script code, because of, as well as despite its flexibility and forgiving nature.

C++ extensions improvement on native PHP performance depends on how much work is hard-coded in a call.

Many of the "standard" extensions exist because of this, such as the regular expression functions and database interfaces. They take advantage of linking to task-optimized algorithms in compiled machine code in external libraries. For example the regular expression string functions of PHP are provided by PCRE, the Pearl Compatible Regular Expressions library, and scripts have benefitted from its upgrades. PHP source builds can choose (or not) to incorporate external library versions distributed along with the php-src archive.

Extensions with a Scripted Helper classes

"Extract" is a PHP Engine linked function used to push an associatred array of arbitrary keyed data into the symbol table of a current executing scripted function.

Extract is very useful for Php-Html templates. Extension functions do not have access to this, no surprise as their stack is their own native code binary, and breaking stack function call discipline of the callee is unthinkable. Closures cannot yet be consstructed by an internal class. Extension classes can implement an "Invoke method". These restrictions are circumvented by callbacks provided by the executing script.

ZPP class Wcc\Plate off loads its html render requirements from "extract" and template output buffering to the purely script-only class "Wcc\ViewOuput".

All this class needs to do its job is to provide a single function of the Interface type "Wcc\IfLoadHtml". I like to start interface class names with "If" because I think it looks good.

// Include the template file after extract of data into the symbol table
interface IfLoadHtml {
     public function gethtml(string $path, array $data) : string;
};

Class Wcc\ViewOuput implements IfLoadHtml, and also extends ServiceAccess. ServiceAccess is also a ZPP extension implemented class. Registered services are accessible inside the included files though the "$this" pointer which is of the ViewOutput class.

The "include" PHP directive means that included file also accesses the local variables of gethtml, plus the extracted variables from the $data.

// part of ViewOutput's gethtml
if ($this->buffer) {
    ob_start();
}
try {
    extract($data);
    unset($data);
    if ($this->label)
    {
        echo $this->comment($path);
    }
    // pull into this symbol world
    include $path;
    if ($this->buffer) {
        $this->output .= ob_get_clean();
    }
}
catch(\Throwable $ex) {...}

The Wcc\Plate class has the job of directing final render calls to its IfLoadHtml handle, with an array of data, in a sequence that renders full HTML page from inside out. This implementation may be set to not use the output buffer, in order to display the called output as generated on a terminal screen from the command line.