symfony 中非共享服务的目的是什么?

Fis*_*her 5 php dependency-injection coding-style symfony

我明白,如果我使用非共享服务,我每次请求该服务时都会获得新实例。这将允许我在此类服务中安全地使用类属性,如果我在共享服务上这样做是不明智的 - 它与并发问题有点相似。

但是,与普通的旧 php 对象相比,非共享服务的优势是什么?

我只能考虑在服务对象内部获得 DI 容器访问权限,但这不是大问题,因为我可以将我需要的内容传递给 POPO 的构造函数或 setter。

我错过了什么吗?

小智 2

对我个人来说,这归根结底是为了方便。是的,您可以使用简单的对象获得几乎相同的功能。但特别是在需要大量依赖项的情况下,将所有依赖项传递到您需要的每个实例上可能会有点麻烦。

只需定义服务及其所需的所有依赖项一次,然后根据需要简单地传递它会更容易。在需要非共享服务的地方,您只传递这个服务,而不是创建对象实例所需的 10 个其他依赖项。

我猜想 YML 中使用非自动装配的示例是:

services:
    App\NonSharedService:
        autowire: false
        shared: false
        arguments:
            - '@dependency1'
            - '@dependency2'
            ...
            - '@dependency15'

    App\RandomService1:
        autowire: false
        arguments:
            - '@App\NonSharedService'

    App\RandomService2:
        autowire: false
        arguments:
            - '@App\NonSharedService'
Run Code Online (Sandbox Code Playgroud)

现在,如果在内部创建 PHP 对象,您需要将所有依赖项传递给以下两者App\RandomService#

services:
    App\RandomService1:
        autowire: false
        arguments:
            - '@dependency1'
            - '@dependency2'
            ...
            - '@dependency15'

    App\RandomService2:
        autowire: false
        arguments:
            - '@dependency1'
            - '@dependency2'
            ...
            - '@dependency15'
Run Code Online (Sandbox Code Playgroud)