mardi 6 mars 2018

Using a factory method with Inversion of control when class type is not known at runtime

I have a question about IOC and when I don't know the class to be instantiated at run-time. For example, I have a few types of View classes. (HtmlView, CsvView, PDFView, etc ) that implement my view interface. The type of view class that I need is determined by user input ( a string in the DB ). I am leaning to using a ViewFactory class that has a make method, the problem is that this will be hiding the View dependency because I only need a ViewFactory.

   class ViewFactory{
        public function make($viewType){
              if($viewType == 'html'){
                 $view = new HtmlView();
              }
              // ...
              return $view   
        }
   } 

   class ReportGenerator{
           public function constructor(Array $data, ViewFactory $viewFactory, String $viewType ){
                 $this->data = $data;
                 $this->view = $viewFactory($viewType);
           }
           public function generate(){
                  return $this->view->render($this->data)
           }
   }   

It seems to me unclear that ReportGenerator depends on a base ViewInterface. Is there a better way, without using a static method.

Aucun commentaire:

Enregistrer un commentaire