如何在Symfony中将服务作为参数注入?

时间:2019-06-28 21:19:50

标签: php symfony service dependency-injection

在Symfony中重写父服务参数并将更多参数添加到子级的正确方法是什么?根据文档,我需要使用“ index_N”。但是如何为子服务添加更多参数呢?例如:

config / services.yaml

服务:     #...

App\Repository\DoctrineUserRepository:
    parent: App\Repository\BaseDoctrineRepository

    # overrides the public setting of the parent service
    public: false

    # appends the '@app.username_checker' argument to the parent
    # argument list
    arguments: ['@app.username_checker']

App\Repository\DoctrinePostRepository:
    parent: App\Repository\BaseDoctrineRepository

    # overrides the first argument (using the special index_N key)
    arguments:
        index_0: '@doctrine.custom_entity_manager'
        // put here more arguments for the child service

1 个答案:

答案 0 :(得分:1)

未经测试,但您是否尝试过使用“命名参数”,例如:

# overrides the first argument (using the special index_N key)
# and set named argument $usernameChecker
arguments:
    index_0: '@doctrine.custom_entity_manager'
    $usernameChecker: '@app.username_checker'