4

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?

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Can you please elaborate on why a service dependency in my model is bad design? It's just some business logic that requires knowledge of a service (security.role_hierarchy). I am using Symfony's validation component extensively for model validation, so that's not the tree I'm barking up.
I'm referring to your entities, as you said an "entity" wants to use a service. This is the bad design as the entities should represent your database objects. If you want define your own service with dependencies then you would just do that using the DIC. It seems like you're asking "How can i inject dependencies without using the DIC"? For that, you just have to manage your own object instantiation and setters and getters.
What then is the purpose of ContainerAware and its related interface? So I guess what you're saying is that model classes have to be defined as services to use automatic constructor dependency injection, and I should manually inject on object instantiation. Thanks for the answers so far.
Model classes should not be defined as services, they shouldn't know about any of that stuff, they're designed to be POPOs.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.