Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 401
Adrian Günter Avatar asked Oct 18 '25 14:10

Adrian Günter


1 Answers

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.

like image 81
MDrollette Avatar answered Oct 20 '25 05:10

MDrollette



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!