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

后端 未结 4 972
醉话见心
醉话见心 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:24

    I find the best way to deal with this is using a factory pattern. You can create a class say ServiceFactory and it has a single method create() it can accept an argument which is used to dynamically choose which concrete class to instantiate.

    It has a case statement based on the argument.

    It will use App::make(ServiceOne::class) or App::make(ServiceTwo::class).depending on which one is required.

    You are then able to inject this into your controller (or service which depends on the factory).

    You can then mock it in a service unit test.

提交回复
热议问题