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)
- you’re not tied to the whole container
- you have a clear overview of all dependency
- you can write code over interfaces instead of concrete implementations
- your classes become more testable
So if you’re using service locator everywhere for your dependencies, I agree that you’re overusing it