-2

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?

  • This is probably not the best place for these sorts of opinion based questions. [Symfony Reddit](https://www.reddit.com/r/symfony/new/) might be a better spot. You might also consider updating your question with a specific example of one of your service locators. In general locators should be used when you don't know in advance exactly which service you need. Should be rare. – Cerad May 03 '23 at 14:09

1 Answers1

0

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

DonCallisto
  • 29,419
  • 9
  • 72
  • 100
  • Thanks for answer. However I have question for each of your points. :) Please answer shortly if you have time: In symfony you are definitely tied to a container. Everything is in container; You must specify your dependencies because you are using ServiceSubscriberInterface; Ok. code over interfaces I got that; By now I can test any of that code. So I still do not see some big problem here. I am using it when I have to decide between multiple steps, depending on some incoming parameter. – Zeljko Miloradovic May 03 '23 at 14:25