Home > Blockchain >  Php multi level inheritance best practice
Php multi level inheritance best practice

Time:01-31

During some workaround with some architecture I faced a question and I am wondering if this implementation follows best practice or not.

Here we have a base abstract class:

abstract class A {

    protected mixed $object;

    public function __construct() {

        $this->loadObject()
             ->fuc1();
    }

    abstract protected function loadObject(): self;
    abstract public function fuc1(): bool;
    abstract public function fuc3(): iterable;
}

In this case, I want to implement Class B and C. if I create each class separately everything is fine but as far as these 2 classes have the same functions I decided to create a base class for them (BC) so codes are now like this:

class BC extends A {

    protected string x;
    protected string y;

    protected function loadObject(): self {
         throw new \Exception('Child must implement loeadObject');
    }
    public function fuc1(): bool {
         //Some Codes
    }
    public function fuc3(): iterable {
        //Some Codes
    }
    
}

And Class B and Class C are like this:

class B extends BC {

    protected function loadObject(): self {
        $this->object = new SomeObject();
        return $this;
    }
}

class C extends BC {

    protected function loadObject(): self {
        $this->object = new SomeObject2();
        return $this;
    }
}

We also can not move loadObject function to class BC cuz maybe class D wants to inherit directly from class A.

We can also rely on interfaces but I was wondering if some one forget to make class B/C implement an Interface then we will have problem in class A.

So is it a good practice that we throw exceptions in the class BC and force other developers to don't forget to overwrite the loadObject function?

CodePudding user response:

This is not a good practice, if you doesn't need to implement the loadObject method in the BC class, you should keep it abstract.

abstract class BC extends A {
    protected string $x;
    protected string $y;

    public function fuc1(): bool {
    }
    public function fuc3(): iterable {
    }
}
  • Related