Adrian Günter
Adrian Günter

Reputation: 910

How do I properly inject dependencies (services) into non-service classes in Symfony2?

I have read the service container chapter in the Symfony2 book multiple times and read SO answers and other resources regarding the topic, but I still just don't seem to get it.

So far, everything I've read has drilled one main truth into my head: the container itself should (practically) never be directly injected into a dependent. This seems to work fine for providing dependencies to other services, but what if an entity in my model wants to inspect the current security context, for instance?

I'm aware that I can implement ContainerAwareInterface and then call setContainer() from a container-aware context to gain access to the container itself in this case, but isn't this the same as injecting the container from the service configuration which is to be avoided at all costs?

Upvotes: 4

Views: 630

Answers (1)

MDrollette
MDrollette

Reputation: 6927

What you describe is just bad design. Your model shouldn't be dependent on the service container. If you need to perform some security checks then you would create a service that has the necessary dependencies injected to it and then pass your model objects to it.

By your example it sounds like you're trying to do validation which is described here http://symfony.com/doc/master/book/validation.html and works much like I stated.

Upvotes: 4

Related Questions