The obvious reason that custom zend_object classes are created, is to recieve calls from and return results to PHP scripts.
It is recommended to write the PHP class outlines and generate registration C code for extension classes using the (classname).stub.php parser. This can also generate interfaces specifications and register them in their entirety.
The generated declarations of the necessary functions to be implemented, can be copied from the *_arginfo.h file to your implementation *.cpp file, because they need to match exactly, otherwise a link error will occur.
In these custom functions to be implemented, the zval arguments passed as an array in the zend_execute_data structure pointed to, need to be checked for presense and having appropriate type.
There is a bunch of PHP approved C macros that are designed do this, which I began to use in the example classes, but eventually I thought I should try to make an alternative C++ class approach.
This is implemented in the zpp/zarg_rd.{h|cpp} files. It probably has a similar processing cost as using the inline macros for processing function arguments. zarg_rd is a class that takes the execute_data pointer as a constructor argument, and its methods can pull out and check requested types associated with argument number position, starting from 0, whether needed or just optional.
Object Memory layout and object management for zpp
ZPP objects allocate their entire C++ class in extra allocated space available below the zend_object structure. This means handling the memory allocation of the objects in the extension.
The object memory layout code is found in the files zpp/base.*
The zpp::base_d class uses its placement new operator to store a pointer plus the entire C++ object below the zend_object. In the allocated block, the zend_object structure sits on top of each C++ class instance, and a pointer to it. A single allocation is done for the combined storage with a call to zend_object_alloc.
Other design possibilities were storing a pointer to the base_obj_mgr
template<typename T>
T* zobj_toc(zend_object* zobj)
{
return *(((T**)(zobj))-1);
}
Going the other way, getting the zend_object* from a base_d class should be as simple, except that inheriting classes will have various increases in size. The simplest approach is to store the zend_object* value as the first protected member of base_d.
//Wcc - include wc_base.h
class base_d {
protected:
zend_object* self_;
public:
// for derived classes
};
Each base\_d class expects to be part of a zend\_object in usage.
base\_d objects cannot safely allocating base\_d objects on the stack. There should be no reasons for copying or moving them around in memory, as can be done with simpler C++ classe and structures. To become part of zend\_object, wierdly allocated base\_d classes would need to be copied into the instance inside its zend\_object class it belongs to.
The life cycle of a zend_object begins with a call to its create_object handler function of its zend_class_entry.
```C++
// part of base_obj_mgr<T>
// typedef base_obj_mgr<T> mydef;
// Create new zpp::obj_rc instance
static obj_rc new_zobj()
{
obj_rc result;
result.adopt(mydef::znew_ex(class_entry_));
return result;
}
Each static instance of base\_obj\_mgr<T> must be configured with its classEntry(zend\_class\_entry*) method during the calls to individual PHP\_MINIT\_FUNCTION(my\_class\_reg).
template< typename T >
class base_obj_mgr : public mgr_link {
/**
* At module init time, one is instantiated for each class T.
*/
public:
typedef base_obj_mgr<T> mydef;
static zend_class_entry* class_entry_;
static zend_object_handlers handlers_;
static base_obj_mgr<T>* self_;
static size_t self_count_;
static size_t obj_count_;
// more
};
For both Zend single and multi-threaded model, during module initialize, these setup their static memory which then becomes read-only during MINIT, and they create dynamic classes with writeable memory during request initialization - RINIT.
So the first 3 members of base_obj_mgr are maybe thread safe, as the base_obj_mgr class instance is created in the PHP_MINIT_FUNCTION, as called from the extensions main PHP_MINIT_FUNCTION. The zend_class_entry* is created by a register_class_<Namespaced_ClassName>. This function and registration information is generated by a script that reads a _stub.php file.
The static obj_count_ function, which I use for debugging to ensure all objects get freed at request end, could be an issue for threaded requests. Currently this is excised for non-debug code.
// In services.h
class Services : base_d {
//...
public:
// define a template type manager for my class
static base_obj_mgr<Services> omg;
};
// In services.cpp
base_obj_mgr<Services> Services::omg;
// Typical PHP extension class initialize in Wcc.
// From wc_services.cpp : create zend_class_entry* from class registration file \_arginfo.h
PHP_MINIT_FUNCTION(wc_services_md)
{
auto ce = register_class_Wcc_Services();
Services::omg.classEntry(ce);
return SUCCESS;
}
The PHP_MINIT_FUNCTION is a C macro, which generates a function name and arguments from its text argument. In the main module initialize function, is a matching call to this function, generated by a similar C-macro.
PHP_MINIT(wc_services_md)(INIT_FUNC_ARGS_PASSTHRU);
Make an object instance
Object instance construction is done by a templated static function of base_obj_mgr. This function knows the class name and thereby its required size, and does a complicated calculation to allocate a memory block, with the C++ object at the start, with its zend_object* stored its first address, and a pointer to C++ object start stored just after the end of the C++ object, after which begins the standard structure of the zend_object, which is what the zend_object* points to.
The C++ object inherits from the base_d class, which has a virtual destructor, and comes with few virtual functions already.
Memory Layout of C++ object - zend\_object
| Layout | Item |
|---|---|
| base_d start | this of zend_object* |
| virtual fn table | Pointer to C++ table of virtual functions |
| derived class members | . . . More class members |
| base_d* | this of C++ object address |
| zend_object | PHP managed zend_object structure |
| object handlers, | |
| PHP property values, |
In each templated singleton, member functions access their own set of static data members, including a zend_class_entry* value which is allocated by the class registration function in module initization.
The memory layout is exactly described by the placement new allocator. Deallocation is managed by the zend_object life cycle.
/**
the easiest way to create a new instance is from the
object manager class new_zobj()
eg obj_rc my_object = Services::omg.new_zobj();
class base_d has a custom operator new.
void* operator new(std::size_t msize, zend_class_entry *ce)
which sets up the above allocation.
*/
static obj_rc new_zobj()
{
// setup object with handlers
obj_rc result;
result.adopt(mydef::make_new());
//showobj("new_zobj()", result);
return result;
}
Customize zend object handlers, using a derived base_obj_mgr
The behaviour of zend_object is depends on its function handlers table, pointed to by its zend_class_entry. Any custom version of base_obj_mgr
for example the Wcc\HMap class, (wcc/hmap.*) overrides init_class_fn() to install custom property handlers, to redirect property value storage into a Hashtable. This is done when the static class manager object classEntry(zend_class_entry*) method is called with zend_class_entry* obtained from the register_class_XXX method in the xxx_arginfo.h created from the stub.php file. From then on, the class manager creates new zend_objects with that information.
Below we hijack the handlers get_debug_info function, and divert it to call base_d objects virtual function, debug_info, so such objects can fill a HashTable with a list of property names and values.
//called from classEntry(zend_class_entry*) function of class manager (base_obj_mgr<T>)
virtual void init_class_fn()
{
class_entry_->create_object = mydef::znew_ex;
// std_object_handlers is somewhere in PHP
memcpy(&handlers_, &std_object_handlers, sizeof(zend_object_handlers));
handlers_.offset = sizeof(T) + sizeof(base_d*);
handlers_.get_debug_info = mydef::base_debug_info;
handlers_.clone_obj = nullptr; //cloning not supported
handlers_.dtor_obj = zend_objects_destroy_object;
handlers_.free_obj = mydef::z_free;
}
Object methods registration
The PHP source release provides a means to set up a default development environment for an extension, and provides a file with the file name type of "
So in the MINIT_FUNCTION scrap above, the function "register_class_Wcc_Services" exists in an _arginfo.h file which was generated from a stub.php, containing a namespace Wcc and a class declaration of Services, with all its public methods. Most all the standard PHP extensions use this feature. It takes away the tedious, error prone work of hand-coding the registration methods, and is thoroughly recommended.
PHP-CPP does not seem to make use of the stub.php to _arginfo.h generation, and requires some manual coding of a registration function for each class. It has its own PHP compatible data structures to hold object registration information, and uses some class handler functions connect these to the PHP engine. This has some declaration limitations derived from the limits of older PHP versions.
Call base_d class methods from PHP C function declarations.
The PHP zend_object method calls are declared and registered from the _arginfo.h generated file(s). The following pattern is used to implement the C function which calls a method of a base_d derived class.
/**
* Implement Services method in wpp.sub.php
*
* public function setObject(object $obj, string|null $key = null) : object {}
*/
// ZEND_METHOD macro generates the function header
ZEND_METHOD(Wcc_Services, setObject)
{
zval* obj;
zend_string* skey = nullptr;
ZEND_PARSE_PARAMETERS_START(1, 2)
Z_PARAM_OBJECT(obj)
Z_PARAM_OPTIONAL
Z_PARAM_STR(skey)
ZEND_PARSE_PARAMETERS_END();
Services* svc = zval_toc<Services>(ZEND_THIS);
val_ptr test(obj); //
obj_ptr result = svc->setObject(test.zobject(), skey);
result.copy_zv(return_value);
}
/* Updated version, as above code is old version*/
ZEND_METHOD(Wcc_Services, setObject)
{
obj_ptr obj;
str_ptr key;
obj_ptr result;
zarg_rd args(execute_data);
args.obj(obj, args.need(0));
args.zstring_null(key, args.option(1));
if (!args.throw_errors())
{
Services* svc = zval_toc<Services>(ZEND_THIS);
// result is now referenced in services
result = svc->setObject(obj, key);
}
// handles potential null
result.copy_zv(return_value);
}
In this not very complex implementation, of the "setObject" method of Wcc\Services, the passed zend_object* is stored in an array (PHP HashTable) accessed by a zend_string key, or its class name, if key is not provided. Usually the object instance is indexed by class name.
Why doesn't this C++ object use an STL collection for greater efficiency? Well it could be done that way, but that is more code for low usage efficiency gain. Here is the actual implementation.
obj_ptr
Services::setObject(obj_ptr obj, str_ptr key)
{
if (key.isNull()) {
// get class name of object
key = obj.className();
}
htab_rw(instances_).set(key, obj);
return obj;
}