Design Patterns – Patterns for Subclass Constructors Varying Parent Class Constructor

constructorsdesign-patternsPHP

So, my problem is in the context of an MVC-style approach. The code here is PHP, but I'm hoping this is a design issue independent of it.

abstract class Controller
{
  private $domain;
  private $view;

  function __construct() {
    $this->domain = new Domain;
    $this->view = new View;
  }
}

So I want to create a series of classes that inherit from this abstract class, such as BlogPageController, or ErrorPageController. The constructors for these subclasses would look something like this:

class BlogPageController
{
  function __construct() {
    $this->domain = new BlogPageDomain;
    $this->view = new BlogPageView;
  }
}

The issue I would like to address is having to always define the constructor for my concrete subclasses – is there a way I can have the parent class Constructor do this, but on the condition that instead of creating (for example) a generic Domain object:

$this->domain = new Domain;

It will create a matching Domain:

$this->domain = new <concrete class>Domain;

As in the example above?

Best Answer

The abstract Controller class can't create the right <concrete class>Domain classes, because it doesn't know which concrete class it belongs to and which Domain and View classes it should be associated with.

What you can do is pass in the Domain and View classes from the derived class's constructor.

abstract class Controller
{
  private $domain;
  private $view;

  function __construct($aDomain, $aView) {
    $this->domain = $aDomain;
    $this->view = $aView;
  }
}

class BlogPageController extends Controller
{
  function __construct() {
    parent::__construct(new BlogPageDomain, new BlogPageView);
  }
}
Related Topic