Nicolas Grekas
Contributed by Nicolas Grekas in #25288

Symfony applications using autowiring can remove most of their service configuration and rely on the injection of services based on argument type-hinting. The main exception to this feature are scalar arguments, such as a service requiring the value of the kernel.project_dir parameter in its constructor.

The solution is simple thanks to argument binding, which lets you define scalar arguments once and apply them to all the services defined in that same config file:

1
2
3
4
5
6
# config/services.yaml
services:
    # ...
    _defaults:
        bind:
            $projectDir: '%kernel.project_dir%'

However, if some particular service needs lots of container parameters (or even all of them, for some edge case feature) using argument binding is cumbersome. In Symfony 4.1 we added a feature to get all container parameters as a service. You just need to type-hint the argument with the ParameterBagInterface class or the new ContainerBagInterface class (which is compatible with the PSR-11 standard):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// src/Service/MessageGenerator.php
// ...

use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;

class MessageGenerator
{
    private $params;

    public function __construct(ParameterBagInterface $params)
    {
        $this->params = $params;
    }

    public function someMethod()
    {
        $parameterValue = $this->params->get('parameter_name');
        // ...
    }
}
Published in #Living on the edge