diff --git a/configuration.rst b/configuration.rst index 4e31c03a3f9..569e70a57f9 100644 --- a/configuration.rst +++ b/configuration.rst @@ -410,6 +410,88 @@ In reality, each environment differs only somewhat from others. This means that all environments share a large base of common configuration, which is put in files directly in the ``config/packages/`` directory. +.. tip:: + + .. versionadded:: 5.3 + + The ability to defined different environments in a single file was + introduced in Symfony 5.3. + + You can also define options for different environments in a single + configuration file using the special ``when`` keyword: + + .. configuration-block:: + + .. code-block:: yaml + + # config/packages/webpack_encore.yaml + webpack_encore: + # ... + output_path: '%kernel.project_dir%/public/build' + strict_mode: true + cache: false + + # cache is enabled only in the "prod" environment + when@prod: + webpack_encore: + cache: true + + # disable strict mode only in the "test" environment + when@test: + webpack_encore: + strict_mode: false + + .. code-block:: xml + + + + + + + + + + + + + + + + + + .. code-block:: php + + // config/packages/framework.php + use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator; + use Symfony\Config\WebpackEncoreConfig; + + return static function (WebpackEncoreConfig $webpackEncore, ContainerConfigurator $container) { + $webpackEncore + ->outputPath('%kernel.project_dir%/public/build') + ->strictMode(true) + ->cache(false) + ; + + // cache is enabled only in the "prod" environment + if ('prod' === $container->env()) { + $webpackEncore->cache(true); + } + + // disable strict mode only in the "test" environment + if ('test' === $container->env()) { + $webpackEncore->strictMode(false); + } + }; + .. seealso:: See the ``configureContainer()`` method of diff --git a/service_container.rst b/service_container.rst index 0e44401bef2..ff1758b1bb3 100644 --- a/service_container.rst +++ b/service_container.rst @@ -222,6 +222,35 @@ each time you ask for it. If you'd prefer to manually wire your service, that's totally possible: see :ref:`services-explicitly-configure-wire-services`. +Limiting Services to a specific Symfony Environment +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. versionadded:: 5.3 + + The ``#[When]`` attribute was introduced in Symfony 5.3. + +If you are using PHP 8.0 or later, you can use the ``#[When]`` PHP +attribute to only register the class as a service in some environments:: + + use Symfony\Component\DependencyInjection\Attribute\When; + + // SomeClass is only registered in the "dev" environment + + #[When(env: 'dev')] + class SomeClass + { + // ... + } + + // you can also apply more than one When attribute to the same class + + #[When(env: 'dev')] + #[When(env: 'test')] + class AnotherClass + { + // ... + } + .. _services-constructor-injection: Injecting Services/Config into a Service