0

Let's say I need a group of classes to implement all of methods X, Y and Z to work properly. In that case, I can let them implement a common interface to force that.

Now, my case is a bit different - my classes need to implement at least one of X, Y and Z, not necessarily all of them. Interfaces can't help me here. The closest thing I can think of is a common parent - it can check the existence of X, Y or Z in its construcor.

I'd rather avoid inheritance here, because I may need to implement this "interface" in a class that already has a parent. So - is there another elegant way to do this?

(I am working in PHP, but if a general OOP solution exists, it may serve to a broader audience.)

Martin Grey
  • 744
  • 2
  • 12
  • 26
  • Interfaces can help you. Have those interfaces extend a common interface. Dunno how you expect to do this without inheritance, unless you want to check which one it is every time. – Jonnix Dec 02 '16 at 09:27
  • 3
    Sounds like a bad architecture/design. Can you please explain (show us you real world scenario) why you need "implements at least one of X,Y,Z"? – Wax Cage Dec 02 '16 at 09:30
  • @WaxCage We have classes for config values access. Some can fetch them from DB, another from config files, another from hardcoded arrays inside them. You can get a value from such a class by getAsString(), getAsParamObject()... or some similar methods. It definitely is a bad design, but it is one that I have to work with for now. These config classes are modified (and broken) often, so I wanted to secure their basic functions (to get the value at least somehow) before I refactor the whole thing. – Martin Grey Dec 02 '16 at 09:44

1 Answers1

1

I'd rather avoid inheritance here, because I may need to implement this "interface" in a class that already has a parent. So - is there another elegant way to do this?

If I understood you correctly, you can solve that issue through Traits:

trait DefaultImpl
{
    public function x()
    {
        echo "Default implementation of x()\n";
    }

    public function y()
    {
        echo "Default implementation of y()\n";
    }

    public function z()
    {
        echo "Default implementation of z()\n";
    }
}

class XImpl
{
    use DefaultImpl;

    public function x()
    {
        echo "Custom implementation of X\n";
    }
}

$x = new XImpl();
$x->x();
$x->y();
$x->z();

It's not a very good solution from design point of view. But it's better than unnecessary inheritance.

Timurib
  • 2,735
  • 16
  • 29