November 9, 2015 Javier Eguiluz

The Dependency Injection component is one of the most important elements of the Symfony applications. This component allows developers to configure services in YAML, XML or PHP files and let Symfony create those services for them.

Services usually define an arguments option listing the arguments passed to their constructors. If the application contains the following two classes:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 namespace AppBundle\Service ; class Service1 { } namespace AppBundle\Service ; use AppBundle\Service\Service1 ; class Service2 { private $service1 ; public function __construct ( Service1 $service1 ) { $this -> service1 = $service1 ; } }

The needed YAML configuration would be the following:

1 2 3 4 5 6 7 8 # app/config/services.yml services : service1 : class : AppBundle\Service\Service1 service2 : class : AppBundle\Service\Service2 arguments : [ '@service1' ]

In Symfony 2.8, thanks to the new service auto wiring feature, you can skip the definition of service1 . The reason is that the service container is able to introspect the constructor parameters, create a private service for Service1 class and inject it into service2 .

This feature is disabled by default and its behavior is restricted to the cases where the services can be guessed unequivocally. You just need to set the new autowire option to true in the services where you want auto wire and let the service container do the rest.

This is how the same service configuration shown before looks like when using auto wiring ( service1 isn't defined explicitly and service2 doesn't define its arguments):

1 2 3 4 5 # app/config/services.yml services : service2 : class : AppBundle\Service\Service2 autowire : true