0

Good morning, i've got a short question about using the container in Symfony.

For me, there are two nice ways to use the container in e.g. a class:

  1. Defining the class as a service and injecting the container in services.yml

  2. Extending the "ContainerAware" class.

What is in this case the best practice ?

jww
  • 97,681
  • 90
  • 411
  • 885
nova.cp
  • 455
  • 1
  • 9
  • 22

1 Answers1

1

that actually depends on a lot of different things. Some people believe that passing around the container is actually bad practice and you should just pass in the services you need instead of pulling them from the container.

For the projects i've worked on that were ok with passing in the container, generally when we created a service we defined the class as a service and injected it in the services.yml, however , when dealing with commands, dispatchers, etc we would just extend the "containerAwareCommand" or "containerAwareEventDispatcher" respectively. The reasoning behind this was that they wanted greater control of their services, but when using things that were specific to symfony (such as the commands) it was probably better to subscribe to the framework methodology.

Derick F
  • 2,749
  • 3
  • 20
  • 30
  • Hi Derick, but where is the difference now when you say "some people don't want to pass the container around" and extending the ContainerAware class ? Because - as i understood - the ContainerAware class is also a service in which symfony injects the container :? I am a bit confused now. Is it because the container only gets injected one time by symfony in the ContainerAware service and not injected by use in other services then ? Is it then better to extend ContainerAware if i don't have other services in the class than injectin only the container ? I 've never used the ContainerAwareCommand. – nova.cp Dec 15 '14 at 11:39
  • @nova.cp what i mean when i say some people don't want to pass the container around is that some people consider to be an anti-pattern. It's referred to as the service locater anti-pattern. Basically, they're against having the container in any classes at all. – Derick F Dec 15 '14 at 15:49
  • @nova.cp my understanding of a the ContainerAware abstract class is that you need to have a calls argument in you services.yml where you set the container (http://stackoverflow.com/questions/17126277/how-to-give-container-as-argument-to-services). Classes like ContainerAwareCommand have a getContainer method that actually pulls the container for you so you don't have to set it. – Derick F Dec 15 '14 at 15:56