vendredi 9 octobre 2020

Constructor injection vs setter factory

I have an class SearchEngine which can have different behaviors and thus I need to pass a search strategy object. Currently I have a setter method in the SearchEngine, which consists of a SearchStrategyFactory

class SearchEngine
{
    protected $strategy;

    public function setStrategy($type)
    {
          $this->strategy = app(SearchStrategyFactory::class)->create($type);
    }

    public function search()
    {
         return $this->strategy->search();
    }

}

My question is if it is a bad design to use a factory class within a method to get an object.

I know that I should better pass the strategy through the constructor or as a parameter in the setter method maybe.

But the way I have it know, I’m avoiding a number of nested if statements.

Of course any suggestion is appreciated.

Aucun commentaire:

Enregistrer un commentaire