(Laravel) Dynamic dependency injection for interface, based on user input

后端 未结 4 935
醉话见心
醉话见心 2021-01-30 17:31

I am currently facing a very interesting dilemma with my architecture and implementation.

I have an interface called ServiceInterface which have a method ca

4条回答
  •  面向向阳花
    2021-01-30 18:31

    The fact that you define that your controller works with ServiceInterface is ok

    If you have to choose the concrete implementation of the service basing on a previous step (that, as i've understood, happens in a previous request) storing the value in session or in database is right too, as you have no alternative: to choose the implementation you have to know the value of the input

    The important point is to 'isolate' the resolution of the concrete implementation from the input value in one place: for example create a method that takes this value as a parameter and returns the concrete implementation of the service from the value:

    public function getServiceImplementation($input_val)
    {
        switch($input_val)
        {
            case 1 : return new Service1();
            case 2 : return new Service2();
        }    
    }
    

    and in your controller:

    public function controllerMethod()
    {
        //create and assign the service implementation
        $this->service = ( new ServiceChooser() )->getServiceImplementation( Session::get('input_val') );
    }
    

    In this example i've used a different class to store the method, but you can place the method in the controller or use a Simple Factory pattern, depending on where the service should be resolved in your application

提交回复
热议问题