phpsymfonyservice-locator

What are bad sides of using Symfony's ServiceLocator?


The college told me that sometimes I overuse ServiceLocator in Symfony 5.4 project. I never considered that possibility. Everything seems straightforward => you get services from the container as you usually do. Instead of using a factory, you use a service locator and you do not care about dependencies.

So, am I right here, or it is possible to overuse ServiceLocator in Symfony? If yes please advice when it is ok to use it?


Solution

  • You should use inversion of control through dependency injection. Main advantages of this approach (in no specific order and maybe I'm forgetting some of them)

    So if you're using service locator everywhere for your dependencies, I agree that you're overusing it