Should “magic” getter functions be used for dynamically calculated values or just existing properties?

For example, if I had a Customer class and wanted to get all orders by them. Would it be better to do:

class Customer{
    public function getOrders(){
        return results from db query
    }
}

...

foreach($customer->getOrders()){}

or

class Customer{
    private function getOrders(){
        return results from db query
    }

    public function __get($attribute){
        if($attribute === 'orders'){
            return $this->getOrders();
        }
    }
}

...

foreach($customer->orders){}

The former isn’t as bloated, but then it’s nice to be able to access it as if it were a property rather than with getOrders().

4

The __get magic method is completely fine, just make sure to couple it either with the @property (if you want a magic __set as well) or @property-read phpDoc annotation so consumers of your class know what they can expect from the public API of your class.

PHP’s combination of __get and __set methods and the @property annotation is a poor-man’s version of C#’s attributes and just like in C#, they’re not bad as long as you show in the API of the class what the class actually offers (in C# you don’t need the annotation for this, because the language supports attributes by default).

I personally don’t use magic __set at all, but have been using __get to a great extent and have never had problems with the method.

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *