1. 云栖社区>
  2. PHP教程>
  3. 正文

New in Symfony 2.8: Service Auto Wiring

作者:用户 来源:互联网 时间:2017-12-01 17:45:22

New in Symfony 2.8: Service Auto Wiring - 摘要: 本文讲的是New in Symfony 2.8: Service Auto Wiring, Contributed by Kévin Dunglas in #15613 . The Dependency Injection component is one of the most important el

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:

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:

# app/config/services.ymlservices:service1:class: AppBundle/Service/Service1service2:class: AppBundle/Service/Service2arguments: ['@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):

# app/config/services.ymlservices: 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.

以上是云栖社区小编为您精心准备的的内容,在云栖社区的博客、问答、公众号、人物、课程等栏目也有的相关内容,欢迎继续使用右上角搜索按钮进行搜索,以便于您获取更多的相关知识。