Search code examples
phpsymfonysymfony4

Symfony manually wiring arguments - 'arguments' vs 'bind'


I try to figure out how to manually inject arguments to DefaultController (without autowiring). And there are two ways I have found to achieve this.

I can use arguments:

services:
    _defaults:
        autowire: false
        autoconfigure: true
        public: true

    App\Service\SomeService: ~

    App\Controller\DefaultController:
        arguments:                                    #!
            $service: '@App\Service\SomeService'
            $scalar: 22

And along with this, I can use bind key:

services:
    _defaults:
        autowire: false
        autoconfigure: true
        public: true

    App\Service\SomeService: ~

    App\Controller\DefaultController:
        bind:                                         #!
            $service: '@App\Service\SomeService'
            $scalar: 22

My controller:

class DefaultController extends Controller
{
    public function __construct($service, $scalar)
    {
        var_dump(get_class($service), $scalar);
    }
...

Both options produce the same output:

string(23) "App\Service\SomeService" int(22)

So what is the difference between this two configuration keys arguments and bind, do they do the exact same thing ?


Solution

  • bind is usually used in the _defaults section to replace any matching argument name in the services that are defined by that file.

    So, taking the variables names from second example, and putting them into the more usual _defaults: stanza

    _defaults:
        # autowire / autoconfig, etc
        bind:                                         #!
            $service: '@App\Service\SomeService'
            $scalar: 22
    

    Any services that had those variable names would be replaced (unless locally overridden) with the service, or scalar value (22).