Child Focused Classes

The Idea!

Object Oriented Programming comes up with a lot of debt – among these, main is how to manage level of inheritance. While it is commonly seen, some classes are parents of others but both parent and child classes are complete class on their own. This will create a mess before you know it. One such place is in models when one table represents more than one type of Entity which is called Single Table Inheritance (STI). For instance, consider an STI for relation between products and tags and orders and tags.

  1. Orders can have tags. N:M
  2. Products can have tags. N:M

Lets assume that you have decided to keep a single table.

Wrong way

Usual but wrong way is:


class TagProduct {
  protected $type="product";

  public function getName(){
    return $this->name;
  }
  public function setName($name){
    $this->name = $name;
    return $this
  }
}


class TagCategory extends TagProduct{
  protected $type="category";
}


Right way


trait TraitSTI
{
  function __construct()
  {
    $this->type = $this->getType();
  }
  protected function getType(){
    return $this->type;
  }
}

Trait ensures that constructor is called to set the type. Otherwise, you have to call parent constructor explicitly if use inheritance.

abstract class TagSTI{
  abstract protected function getType();
  public function getName(){
    return $this->name;
  }
  public function setName($name){
    $this->name = $name;
    return $this;
  }
}

This is the key here. TagSTI class in itself is an incompetent class. Thus, only way to solve the problem is to use Children.

abstract class TagSTI{
  abstract protected function getType();
  public function getName(){
    return $this->name;
  }
  public function setName($name){
    $this->name = $name;
    return $this;
  }
}

This is the key here. TagSTI class in itself is an incompetent class. Thus, only way to solve the problem is to use Children.


class TagCategory extends TagSTI{
  use TraitSTI;
  protected $type = "category";
}


class TagProduct extends TagSTI{
  use TraitSTI;
  protected $type = "product";
}

Child Focused Classes

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top