vendredi 18 décembre 2015

One Class Asking Several Classes to Perform The Same Task

I have a Laravel App and I'm creating a class that imports data. The data is being stored in about 15 different models, so I have a Class to handle each as each has its own implementation. Furthermore, more models may be added in the future.

I'd like to have a line of code like $importer->import() in an Importer class, which then takes all 15 of the implementation classes, and calls their import() methods.

However, the generic $importer->import() method will then look like:

public function __construct(ImporterOne $one, ImporterTwo $two, ImporterThree $three, etc..)
{
   $this->importerOne = $importerOne;
   $this->importerTwo = $importerTwo;
   // etc ...
   $this->importerFifteen = $importerFifteen;
}

public function import()
{
    $this->importerOne->import();
    $this->importerTwo->importer();
    // etc...
}

This doesn't seem very good because this class will then have 15+ dependences all essentially doing the same thing. And then to update this, I'll need to go in here and Add / Remove dependencies and import() method calls.

So my solution is to delegate the the 'registration' of importers to each implementation, rather than leaving the Generic Importer class responsible. Effectively, an Observer of sorts. But instead of the client attaching the Observer to the Subject, each implementation attaches itself to the Subject.

use Importer as GenericImporter

public class importerOne {

   public function __construct(SomeModel $model, GenericImporter $importer)
   {
      $this->importer = $importer;
      $this->importer->attach($this);
   }
}

// Do the same for each implementation

// and then the generic importer

public class Importer {

   protected $importables = [];

   public function attach($import_implementation)
   {
      array_push($importables, $import_implementation); 
   }

   public function import()
   {
      foreach($this->importables as $importable)
      {
          $importable->import();
      }
   }

}

This seems nice and SOLID. However, the problem is that each implementation is now using their OWN instance of the GenericImporter. So whats the best way to go about this? Do I implement the Generic Importer as a Singleton? Also, for my research purposes, does this fall into a certain design pattern? It seems similar to an ObservorPattern except that each Observer is registering itself.

Aucun commentaire:

Enregistrer un commentaire