Symfony:将对象(不是服务)注入到服务构造函数中 [英] Symfony: Inject object (not service) to service constructor

查看:23
本文介绍了Symfony:将对象(不是服务)注入到服务构造函数中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的服务定义中,我想将对象而不是服务作为服务参数构造函数传递.

In the definition of my services, I'd like to pass as a service argument constructor an object not a service.

来自 config.yml:

From config.yml:

services:
  acme.services.exampleservice:
    class:  Acme\ExampleBundle\Services\ExampleService
    arguments: 
        entityManager: "@doctrine.orm.entity_manager"
        httpClient: \Example\Http\Client\Client

注意 httpClient 参数.这必须是 \Example\Http\Client\Client 类的实例.

Note the httpClient argument. This must be an instance of the \Example\Http\Client\Client class.

以上不起作用 - 字符串\Example\Http\Client\Client"作为 httpClient 参数传递给服务.

The above does not work - the string "\Example\Http\Client\Client" is passed as the httpClient argument to the service.

通过将\Example\Http\Client\Client 的实例传递给服务构造函数来实现上述目的的语法是什么?

What is the syntax for achieving the above by means of passing an instance of \Example\Http\Client\Client to the service constructor?

推荐答案

创建私有服务.以下是文档中的内容:

Create a private service. Here's what's written in the documentation:

如果您使用私有服务作为多个其他服务的参数,这将导致使用两个不同的实例,因为私有服务的实例化是内联完成的(例如 new PrivateFooBar()).

If you use a private service as an argument to more than one other service, this will result in two different instances being used as the instantiation of the private service is done inline (e.g. new PrivateFooBar()).

services:
  acme.services.exampleservice:
    class:  Acme\ExampleBundle\Services\ExampleService
    arguments: 
        entityManager: "@doctrine.orm.entity_manager"
        httpClient: acme.services.httpClient

  acme.services.httpClient:
    class: Example\Http\Client\Client
    public: false

您将无法从容器中检索私有服务.从外部看,它就像您将常规对象传递给服务的构造函数一样.

You will not be able to retrieve a private service from the container. From the outside it looks just as if you passed a regular object to the constructor of your service.

这篇关于Symfony:将对象(不是服务)注入到服务构造函数中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆