mardi 24 mars 2015

Multiple method calls in the constructor and dependency injection


I was asked to refactor some almost ureadable spaghetti code into object-oriented architecture.


I have some doubts regarding a class that I designed. Here is the class' skeleton:



require_once 'inc/FeaturedCarousel/Carousel.php';
class FeaturedCarousel
{
private $currentCategory;
private $allFeaturedAdvertisers = array();
private $metaData = array();
private $featuredAdvertisersIds = array();
private $dataForDisplay = array();

public function __construct($currentCategory)
{
$this->currentCategory = $currentCategory;
$this->getAllFeaturedAdvertisers();
$this->getAllAdvertisersMetaData();
$this->getFeaturedAdvertisersInCurrentCategory();
$this->getDataForDisplay();
}

private function getAllFeaturedAdvertisers()
{
}

private function getAllAdvertisersMetaData()
{
}

private function getFeaturedAdvertisersInCurrentCategory()
{
}

private function getDataForDisplay()
{
}

public function displayCarousel()
{
new FeaturedCarousel\Carousel($this->dataForDisplay);
}
}


The class is initiated like this:



$carousel = new FeaturedCarousel($currentCategory);
$carousel->displayCarousel();


The class' role is to prepare data for display, and then display it using an external Carousel class that is instantiated in the displayCarousel() method.


There may be major aspects of it that should refactored. Please note that I have already implemented all the methods so there is no need to focus on their implementation.


Here are my questions -




  1. All methods required to generate data for display are trigerred one by one in the constructor. Each of these methods generates a private property required by the method called next. Therefore, if any of the methods fails, there is really no point in calling subsequent methods. How should I address those possible method failures?




  2. The displayCarousel() method instantiates another class that is responsible for the actual rendering of HTML content. At the moment the Carousel class is just required and instantiated in the method call. Should the Carousel class be 'injected' into my class before it is used?







Aucun commentaire:

Enregistrer un commentaire