Search code examples
phpsymfonydependency-injectionsymfony-dependency-injection

How to represent argument that uses factory with YAML configuration, equivalent to this XML configuration?


I am trying to figure out if I can use a similar construct in the YAML syntax for a service definition as in the XML syntax. Specifically the "construct" where, in XML, an argument can be resolved by factory "in-line".

I have the following XML definition:

<service id="my_service_id" class="App\Some\Service">
    <argument type="service">
        <service class="Gaufrette\Filesystem">
            <argument>%some_container_parameter%</argument>
            <factory service="knp_gaufrette.filesystem_map" method="get" />
        </service>
    </argument>
    <argument type="service" id="request_stack"/>
    <argument>%some_other_container_parameter%</argument>
</service>

I can't figure out how to represent this (or if it's even possible) in yaml.

I have tried the following:

my_service_id:
    class: App\Some\Service
    arguments:
        - { class: Gaufrette\Filesystem, factory: ['@knp_gaufrette.filesystem_map','get'], arguments: ['%some_container_parameter%'] }
        - '@request_stack'
        - '%some_other_container_parameter%'

but that gives me the following error message:

Argument 1 passed to App\Some\Service::__construct() must implement interface Gaufrette\FilesystemInterface, array given


Solution

  • You are defining two services within the same definition in the XML version.

    While that is possible in XML, I don't really think it's a great idea. You can easily do the same by defining each service on its own:

    gaufrette.filesystem:
        factory: ['@knp_gaufrette.filesystem_map','get']
        arguments: ['%some_container_parameter%']
    
    my_service_id:
        class: App\Some\Service
        arguments:
            - '@gaufrette.filesystem'
            - '@request_stack'
            - '%some_other_container_parameter%'