简体   繁体   中英

How to inject service as argument in Symfony?

What is the correct way in Symfony to override the parent service argument and also add to the children more arguments? According to the documentation, I need to use "index_N". But how to add more arguments to the child service? In example:

config/services.yaml

services: # ...

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

Untested, but did you try using "named arguments", like here:

# 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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM