diff --git a/.doctor-rst.yaml b/.doctor-rst.yaml index 2f0d5852c7f..132bc39d689 100644 --- a/.doctor-rst.yaml +++ b/.doctor-rst.yaml @@ -122,3 +122,4 @@ whitelist: - 'End to End Tests (E2E)' - '.. versionadded:: 2.2.0' # Panther - '* Inline code blocks use double-ticks (````like this````).' + - '- !php/const App\Service\AnotherService::SOME_CONSTANT' diff --git a/service_container.rst b/service_container.rst index c1f5dc7b5f4..645717aecb4 100644 --- a/service_container.rst +++ b/service_container.rst @@ -323,6 +323,127 @@ type-hints by running: [...] +In addition to injecting services, you can also pass scalar values and collections +as arguments of other services: + +.. configuration-block:: + + .. code-block:: yaml + + # config/services.yaml + services: + App\Service\SomeService: + arguments: + # string, numeric and boolean arguments can be passed "as is" + - 'Foo' + - true + - 7 + - 3.14 + + # constants can be built-in, user-defined, or Enums + - !php/const E_ALL + - !php/const PDO::FETCH_NUM + - !php/const App\Service\AnotherService::SOME_CONSTANT + - !php/const App\Config\SomeEnum::SomeCase + + # when not using autowiring, you can pass service arguments explicitly + - '@some-service-id' # the leading '@' tells this is a service ID, not a string + - '@?some-service-id' # using '?' means to pass null if service doesn't exist + + # binary contents are passed encoded as base64 strings + - !!binary VGhpcyBpcyBhIEJlbGwgY2hhciAH + + # collections (arrays) can include any type of argument + - + first: !php/const true + second: 'Foo' + + .. code-block:: xml + + + + + + + + + Foo + 7 + 3.14 + + Foo + + true + + + E_ALL + PDO::FETCH_NUM + App\Service\AnotherService::SOME_CONSTANT + App\Config\SomeEnum::SomeCase + + + + + + VGhpcyBpcyBhIEJlbGwgY2hhciAH + + + + true + Foo + + + + + + + + .. code-block:: php + + // config/services.php + namespace Symfony\Component\DependencyInjection\Loader\Configurator; + + use Symfony\Component\DependencyInjection\ContainerInterface; + use Symfony\Component\DependencyInjection\Reference; + + return static function (ContainerConfigurator $container) { + $services = $container->services(); + + $services->set(App\Service\SomeService::class) + // string, numeric and boolean arguments can be passed "as is" + ->arg(0, 'Foo') + ->arg(1, true) + ->arg(2, 7) + ->arg(3, 3.14) + + // constants: built-in, user-defined, or Enums + ->arg(4, E_ALL) + ->arg(5, \PDO::FETCH_NUM) + ->arg(6, App\Service\AnotherService::SOME_CONSTANT) + ->arg(7, App\Config\SomeEnum::SomeCase) + + // when not using autowiring, you can pass service arguments explicitly + ->arg(8, service('some-service-id')) # fails if service doesn't exist + # passes null if service doesn't exist + ->arg(9, new Reference('some-service-id', Reference::IGNORE_ON_INVALID_REFERENCE)) + + // collection with mixed argument types + ->arg(10, [ + 'first' => true, + 'second' => 'Foo', + ]); + + // ... + }; + Handling Multiple Services ~~~~~~~~~~~~~~~~~~~~~~~~~~