ServiceLocator, let's thoughts about it in ZF2 context

前端 未结 1 1448
走了就别回头了
走了就别回头了 2021-01-13 01:38

According to Marco\'s Pivetta thoughts with this, this old question and my answer to an other question

I was interrogating myself about the better way to use our Ser

1条回答
  •  隐瞒了意图╮
    2021-01-13 02:39

    Let's say you would inject the ServiceLocator instance. There is no guarantee that the ServiceLocator actually holds your hard dependencies, thus breaking the DI pattern. When using constructor dependency injection you are sure that all the services that are needed are really available. If not, the constructing of the service will simply fail.

    When using a ServiceLocator you will end up in an instantiated service class where hard dependencies might or might not be available through the ServiceLocator. This means you have to write all kind of additional logic (check dependencies, throw exceptions) in case the dependency cannot be resolved from the ServiceLocator instance the moment you ask for it. Writing all this code will probably be much more work then injecting 15 dependencies and on top of that the logic will be cluttered all over your service.

    Additionally you would still need to add all the setter and getter methods to be able to get your services from your ServiceLocator and to make your service testable.

    IMHO injecting 15 dependencies is less code and easier to maintain then injecting a ServiceLocator instance.

    0 讨论(0)
提交回复
热议问题