Symfony News

New in Symfony 2.8: Service Auto Wiring

Kévin Dunglas

Contributed by
Kévin Dunglas
in #15613.

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\Service1;

class Service1
{
}

namespace AppBundle\Service\Service2;

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

Service auto wiring was pioneered more than 10 years ago by the Spring Java framework with their @Autowired annotation and it's a feature best suited for simplifying the development of application prototypes.


Be trained by Symfony experts - 2015-11-16 Clichy - 2015-11-16 Clichy - 2015-11-18 Clichy


About us

What a Symfony developer should know about the framework: News, Jobs, Tweets, Events, Videos,...

Resources

Find us on Twitter

Find us on Facebook