Working with objects

Getting end users to grasp the concept of data structures is no easy task. While the concept of objects having properties (for instance, a customer having a first name and a last name) is usually easy to convey, you probably would not bother end users with things like data encapsulation and object methods.

Because of this, it might be useful to hide the intricacies of data access from your end user; if a user want to access a customer's first name, they should be able to write customer.firstname, even if the actual property of the underlying object is protected, and you would usually need to call a getFirstname() method to read this property. Since getter functions typically follow certain naming patterns, our parser can automatically translate expressions such as customer.firstname to method calls such as $customer->getFirstname().

To implement this feature, we need to extend the evaluate method of PropertyFetch by a few special cases:

public function evaluate(array $variables = []) 
{ 
    $var = $this->left->evaluate($variables); 
    if (is_object($var)) {

        $getterMethodName = 'get' . ucfirst($this->property);

        if (is_callable([$var, $getterMethodName])) {

            return $var->{$getterMethodName}();

        }
        $isMethodName = 'is' . ucfirst($this->property);

        if (is_callable([$var, $isMethodName])) {

            return $var->{$isMethodName}();

        }

        return $var->{$this->property} ?? null;

    }
return $var[$this->property] ?? null; 
} 

Using this implementation, an expression such as customer.firstname will first check if the customer object implements a getFirstname()method that can be called. Should this not be the case, the interpreter will check for an isFirstname() method (which does not make sense in this case, but could be useful as getter functions, for Boolean properties are often named isSomething instead of getSomething). If no isFirstname() method exists either, the interpreter will look for an accessible property named firstname, and then as a last resort simply return null.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.15.214.27