Back

Code review for improvement


Ricardo posted 4 months ago

Hi there!

I have a bunch of accessor and I want to receive suggestions on how to improve it.

public function getHddAttribute()
{
    return $this->hasComponent('hdd');
}

public function getSddAttribute()
{
    return $this->hasComponent('sdd');
}

public function getHdmiAttribute()
{
    return $this->hasComponent('hdmi');
}

public function getUsb3Attribute()
{
    return $this->hasComponent('usb3');
}

private function hasComponent($component)
{
    return array_search($component, self::$components);
}

Thank you in advance.

lagbox replied 4 months ago

How to improve what about it?

Ricardo replied 4 months ago Solution

There are some many accessors, it can be reduced as follows:

public function __get($var)
{
    if (($key = array_search($var, self::$components)) == false) {
        return parent::__get($var);
    }

    return $this->hasComponet($var);
}

All accessors referring to a component are unnecessary now.


Sign in to participate in this thread!



We'd like to thank these amazing companies for supporting us