Using objects - obj_ptr, obj_rc

The zpp::obj_ptr wraps a zend_object* , to access methods without reference counting. It includes some methods to make unoptimised calls to an object's named methods, with capacity for up to four zval* arguments, and may write to named properties, with some allowance for C++ style function overload name mangling for the types of property as str_ptr, obj_ptr, val_ptr, htab_ptr and int types. Read of specific return types of different property types is facilited with the name of the read functions as <class-type>_property(str_ptr key). These are hard coded, there are no templates here.

The generic val_rc return type gets whatever it finds. These functions work best with PHP public properties. Access to private and protected hasn't been played with.

class obj_ptr {
    protected:
        zend_object* obj_;

        friend class obj_rc;
        friend class weak_ref;
        
    public:
    //... property
    //! get a public  property value by string name
        val_rc    property(str_ptr key);
        htab_rc   array_property(str_ptr key);
        str_rc    str_property(str_ptr key);
        obj_rc    obj_property(str_ptr key);
        zend_long int_property(str_ptr key);


        zval* 	  property_get(str_ptr key, zval* ret);

        val_ptr   property_ptr(str_ptr key);
        
        //! set a public property value, overloaded functions
        void      property(str_ptr key, val_ptr value);
        void      property(str_ptr key, str_ptr value);
        void      property(str_ptr key, obj_ptr value);
        void      property(str_ptr key, val_rc& value);
        void      property(str_ptr key, htab_ptr value);
        void      property(str_ptr key, int value);
        
        bool      has_property(str_ptr name);
        void      unset_property(str_ptr name);
        //! property-values list
        htab_rc  properties();
        
        //! Closures, isCallables
        val_rc callable();
        val_rc callable(zval* arg1);
        val_rc callable(zval* arg1, zval* arg2);
        
        // User responsible for prepping 1 to 4 arguments
        // which are simply ZVAL_COPY_VALUE into temporary C zval array
        // argument reference counting need not be done.
        val_rc call(str_ptr method, 
            zval* arg1, zval* arg2, zval* arg3, zval* arg4)


Such an object may be a "special" callable object, such as an anonymous function, or object with an invoke method. Wcc\Services checks for this possibility on any named service. The obj_ptr callable methods exist for zero, one, or two arguments. They use the callable_fn method declared in fn_call.h, which can use any number of arguments.

// Wcc\\Services passes itself to callables as zend_object* first argument
val_rc Services::call_value(obj_ptr callme)
{
    val_rc self(this);
    return callme.callable(self);
}

// in Services::get
val_ptr value;
if (test.isCallable())
{
    obj_ptr callme = test.zobject();
    val_rc result = call_value(callme);
}

The obj_ptr call methods all take a str_ptr as first argument, the method name. Method overrides exist for up to four zval* arguments. Each uses a fn_call_args template internally. The fn_call class also supports passing named arguments as a HashTable*, using its set_named_args(HashTable*) method.

Get a self obj_ptr from C++ class (zend_object*)

Like val_rc, obj_ptr has among its constructors one which takes a base_d\* argument, which sets the obj_ptr to the zend_object\* value held by the base_d\* member this->self\_. For convenience the base_d class has a self() method to provide an obj_ptr from this.
    
/**
    Template function to get back to C++ object from zend_object* 
*/
    
template<typename T>
    T* zobj_toc(zend_object* zobj)
    {
        return *(((T**)(zobj))-1);
    }
    
/**
    @class base_d 
    Base class for placement below a zend_object structure.
    This is placement new embedded below the zend_object structure, just below 
    a pointer to its C++ instance.
*/
class   base_d {
    protected:
            zend_object* self_;
    public:
                zend_object* vobj() const { return self_; }
                obj_ptr self() const { return obj_ptr(self_); }
    //...
                virtual void debug_info(htab_rw ht);

                virtual str_rc toString() const {
                    return str_rc();
                };
    };
    
    

Sharing PHP object properties with C++

PHP byte code efficiency is optimized by the interpreter having known offsets for declared class properties. This maybe explains efforts to deprecate use of dynamic properties in objects, unless the class type is specifically tagged as allowing them, or has magic methods to process them. The result is warnings or exceptions are thrown when trying to access properties that don't exist, in objects not so configured.

Typical PHP properties are easily generated for C++ classes, by including the C code generated from PHP declarations in *.stub.php files. C++ code has to access to the values of such properties via obj_ptr property methods.

Comparing different methods of named property access

Wcc PHP objects in C++ have an example of a dynamic property oriented class - Wcc\Config , and also Wcc\Hmap class, which internally uses a PHP array to store properties.

Accessing properties and array values by string keys is the mainstay of PHP coding. To compare the efficiency of various kinds of PHP property/value access by key name, I created a script that repeated a numeric sum and division ( a + b ) / a, and averaged the time taken over a large number of iterations. The following table shows the kind of entity, and results ratioed two of chosen methods, being just local variables, and object-declared property. Compared are local array with string keys, dynamic property objects, and object properties implemented as array storage, and a call to a function implemented as a method of Wcc\Pair, just for this purpose.

The ratio of averaged times to complete are formatted to 2 decimal places here.

Implementation X / Local variable (e) X / fixed property access (a)
Local variables (e) 1 0.6
Wcc\Pair (C++) declared properties (a) 1.66 1
EmptyTest (PHP) declared properties (i) 1.66 1
Wcc\Pair call test_calc() (c) 1.77 1.07
Wcc\Pair (C++) methods get (b) 3.36 2.03
Wcc\Config dynamic properties 1.78 1.08
Use local array (g) 2.14 1.29
Extend stdClass (h) 3.81 2.3
Hmap property handler (f) 2.92 1.76
Hmap array handler (m) 3.78 2.28
ArrayObject as [array] (k) 4.97 3
ArrayObject ->Property (j) 5.14 3.11

The results suggest the unsurprising find that using script function local variables is optimal, and object access to declared properties take about 67% more time. For any none trivial calculation, a method call to compiled code (c) is good. Even for a trivial calculation, doing it within a declared method is faster than using get method (b) 3 times for doing calculation inline locally.

All of the short statements looping repeat processes are fast, presumed CPU caches work well, since each of the 12 test functions timed a loop of 1000 iterations, and the whole sequence repeated 1000 times, which makes for 12 million iterations, and on a modern x86_64 processor, only took a few seconds.

Dynamic properties a little bit slower. Property handlers seem faster than array handlers. Except for the "ArrayObject" in its "ARRAY_AS_PROPS" setup, which lagged the others, for reasons I cannot explain.

Wcc\Config and Wcc\Hmap are into the Wcc extension using the ZPP / base_d C++ classes. They seem okay for simple uses they are reasonably effective at basic get/set compared to ArrayObject, but may have some issues for complex expression requirement.

The script that produced this table is "tests/pairs.php". This was done a while ago, and this developer is tired of maintaining and re-running it.

Custom function calls

The obj_ptr call(method, ...args) function uses very much the same code as some of the already optimized calls to some common PHP functions defined at module init time in zpp/fn_call.h

A fn_call class defines the method/function name, and optional object instance. The name is the first and most essential argument. A template fn_params<uint> class creates some "cleaned" zval array space. Or fn_noparams, for zero arguments. The arguments are set or copied in the zval array space. The fn_params class also has the return result zval, and a method to call the function and return some kind PHP result type wrapper.

//...
    class fn_call {
    protected:
        zend_fcall_info       fci_;
        zend_fcall_info_cache cache_;

        void init_f();
        
        friend class fn_result;
    public:

          fn_call();
        fn_call(zend_string* method);
        fn_call(zend_string* method, zend_object* obj);
    //...
    };
    
    class fn_result {
    protected:
        fn_call&  cfi_;

        fn_result(fn_call& fn) : cfi_(fn), result_({})
        {
            cfi_.fci_.retval = &result_;
        }
            //! call with expected void return type
        bool    call_fn();

        void    throw_failed();
        
        //! Call for various expected return types */
        val_rc  mixed();
        str_rc  str();
        obj_rc  obj();
        bool    zbool();
        htab_rc array();
        zend_long zlong();
    };
    
    template <size_t ARGCT> class fn_params : public fn_result {
  public:
        zval      params[ARGCT];
    
      fn_params(fn_call& fn) : fn_result(fn)
        {
                //does first wipe
                setParams(¶ms[0], ARGCT);
        }
    //....
        zval* argsptr() { return params; /*¶ms[0];*/ }
    };
val_rc
obj_ptr::call(str_ptr method, zval* arg1)
{
    fn_call objcall(method, obj_);
    fn_params<1> fn(objcall);

    zval* zv = fn.argsptr();

    ZVAL_COPY_VALUE(zv, arg1);

    return fn.mixed();
}

Discovering memory issues.

For use in repeated request processes, such as php-fpm workers, its important to clean the request memory up each time. So some attention has been given to test extensions made with Wcc for memory issues. This mean running the extension with a version of PHP compiled in debug mode, and sometimes running a test script using valgrind. Such testing uncovered instances of memory leak behaviour, expecially when scripts terminated abruptly without cleanup.

Defeat circular references

The Wcd namespace featured a few cases of circular pointer object references, and efforts were made, by employing object __destruct methods, and even using a weakref for the IDriver class, which was thrown all over the place, to ensure all objects get freed. 

All the *_rc classes "should", under typical use, are expected to balance their reference counts during standard C++ class instance management.

Missing features, and likely changes

Things are likely to be missing, or or found to need changing, when and if other people use these for unthought of contexts.

Script compatibility

The Wcc and Wcd classes have their script-only objects and functions have been kept in near parallel compatibility with their compiled wcc extension versions. This makes it easier to test for changes in design before hard-coding or modifying C++ class counterparts. This isn't possible for every kind of context, and the second level of compatibility is hidden functional analogy where capability differs.