Configuring Symfony

Configuring Symfony

Configuration Files

Symfony applications are configured with the files stored in the config/ directory, which has this default structure:

  1. your-project/
  2. ├─ config/
  3. ├─ packages/
  4. ├─ bundles.php
  5. ├─ routes.yaml
  6. └─ services.yaml
  7. ├─ ...

The routes.yaml file defines the routing configuration; the services.yaml file configures the services of the service container; the bundles.php file enables/ disables packages in your application.

You’ll be working mostly in the config/packages/ directory. This directory stores the configuration of every package installed in your application. Packages (also called “bundles” in Symfony and “plugins/modules” in other projects) add ready-to-use features to your projects.

When using Symfony Flex, which is enabled by default in Symfony applications, packages update the bundles.php file and create new files in config/packages/ automatically during their installation. For example, this is the default file created by the “API Platform” package:

  1. # config/packages/api_platform.yaml
  2. api_platform:
  3. mapping:
  4. paths: ['%kernel.project_dir%/src/Entity']

Splitting the configuration into lots of small files is intimidating for some Symfony newcomers. However, you’ll get used to them quickly and you rarely need to change these files after package installation

Tip

To learn about all the available configuration options, check out the Symfony Configuration Reference or run the config:dump-reference command.

Configuration Formats

Unlike other frameworks, Symfony doesn’t impose a specific format on you to configure your applications. Symfony lets you choose between YAML, XML and PHP and throughout the Symfony documentation, all configuration examples will be shown in these three formats.

There isn’t any practical difference between formats. In fact, Symfony transforms and caches all of them into PHP before running the application, so there’s not even any performance difference between them.

YAML is used by default when installing packages because it’s concise and very readable. These are the main advantages and disadvantages of each format:

  • YAML: simple, clean and readable, but not all IDEs support autocompletion and validation for it. Learn the YAML syntax;
  • XML:autocompleted/validated by most IDEs and is parsed natively by PHP, but sometimes it generates configuration considered too verbose. Learn the XML syntax;
  • PHP: very powerful and it allows you to create dynamic configuration, but the resulting configuration is less readable than the other formats.

Importing Configuration Files

Symfony loads configuration files using the Config component, which provides advanced features such as importing other configuration files, even if they use a different format:

  • YAML

    1. # config/services.yaml
    2. imports:
    3. - { resource: 'legacy_config.php' }
    4. # glob expressions are also supported to load multiple files
    5. - { resource: '/etc/myapp/*.yaml' }
    6. # ignore_errors: not_found silently discards errors if the loaded file doesn't exist
    7. - { resource: 'my_config_file.xml', ignore_errors: not_found }
    8. # ignore_errors: true silently discards all errors (including invalid code and not found)
    9. - { resource: 'my_other_config_file.xml', ignore_errors: true }
    10. # ...
  • XML

    1. <!-- config/services.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <container xmlns="http://symfony.com/schema/dic/services"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xsi:schemaLocation="http://symfony.com/schema/dic/services
    6. https://symfony.com/schema/dic/services/services-1.0.xsd
    7. http://symfony.com/schema/dic/symfony
    8. https://symfony.com/schema/dic/symfony/symfony-1.0.xsd">
    9. <imports>
    10. <import resource="legacy_config.php"/>
    11. <!-- glob expressions are also supported to load multiple files -->
    12. <import resource="/etc/myapp/*.yaml"/>
    13. <!-- ignore-errors="not_found" silently discards errors if the loaded file doesn't exist -->
    14. <import resource="my_config_file.yaml" ignore-errors="not_found"/>
    15. <!-- ignore-errors="true" silently discards all errors (including invalid code and not found) -->
    16. <import resource="my_other_config_file.yaml" ignore-errors="true"/>
    17. </imports>
    18. <!-- ... -->
    19. </container>
  • PHP

    1. // config/services.php
    2. namespace Symfony\Component\DependencyInjection\Loader\Configurator;
    3. return static function (ContainerConfigurator $container) {
    4. $container->import('legacy_config.php');
    5. // glob expressions are also supported to load multiple files
    6. $container->import('/etc/myapp/*.yaml');
    7. // the third optional argument of import() is 'ignore_errors'
    8. // 'ignore_errors' set to 'not_found' silently discards errors if the loaded file doesn't exist
    9. $container->import('my_config_file.yaml', null, 'not_found');
    10. // 'ignore_errors' set to true silently discards all errors (including invalid code and not found)
    11. $container->import('my_config_file.yaml', null, true);
    12. };
    13. // ...

New in version 4.4: The not_found option value for ignore_errors was introduced in Symfony 4.4.

Configuration Parameters

Sometimes the same configuration value is used in several configuration files. Instead of repeating it, you can define it as a “parameter”, which is like a reusable configuration value. By convention, parameters are defined under the parameters key in the config/services.yaml file:

  • YAML

    1. # config/services.yaml
    2. parameters:
    3. # the parameter name is an arbitrary string (the 'app.' prefix is recommended
    4. # to better differentiate your parameters from Symfony parameters).
    5. app.admin_email: '[email protected]'
    6. # boolean parameters
    7. app.enable_v2_protocol: true
    8. # array/collection parameters
    9. app.supported_locales: ['en', 'es', 'fr']
    10. # binary content parameters (encode the contents with base64_encode())
    11. app.some_parameter: !!binary VGhpcyBpcyBhIEJlbGwgY2hhciAH
    12. # PHP constants as parameter values
    13. app.some_constant: !php/const GLOBAL_CONSTANT
    14. app.another_constant: !php/const App\Entity\BlogPost::MAX_ITEMS
    15. # ...
  • XML

    1. <!-- config/services.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <container xmlns="http://symfony.com/schema/dic/services"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xmlns:framework="http://symfony.com/schema/dic/symfony"
    6. xsi:schemaLocation="http://symfony.com/schema/dic/services
    7. https://symfony.com/schema/dic/services/services-1.0.xsd
    8. http://symfony.com/schema/dic/symfony
    9. https://symfony.com/schema/dic/symfony/symfony-1.0.xsd">
    10. <parameters>
    11. <!-- the parameter name is an arbitrary string (the 'app.' prefix is recommended
    12. to better differentiate your parameters from Symfony parameters). -->
    13. <parameter key="app.admin_email">[email protected]</parameter>
    14. <!-- boolean parameters -->
    15. <parameter key="app.enable_v2_protocol">true</parameter>
    16. <!-- if you prefer to store the boolean value as a string in the parameter -->
    17. <parameter key="app.enable_v2_protocol" type="string">true</parameter>
    18. <!-- array/collection parameters -->
    19. <parameter key="app.supported_locales" type="collection">
    20. <parameter>en</parameter>
    21. <parameter>es</parameter>
    22. <parameter>fr</parameter>
    23. </parameter>
    24. <!-- binary content parameters (encode the contents with base64_encode()) -->
    25. <parameter key="app.some_parameter" type="binary">VGhpcyBpcyBhIEJlbGwgY2hhciAH</parameter>
    26. <!-- PHP constants as parameter values -->
    27. <parameter key="app.some_constant" type="constant">GLOBAL_CONSTANT</parameter>
    28. <parameter key="app.another_constant" type="constant">App\Entity\BlogPost::MAX_ITEMS</parameter>
    29. </parameters>
    30. <!-- ... -->
    31. </container>
  • PHP

    1. // config/services.php
    2. namespace Symfony\Component\DependencyInjection\Loader\Configurator;
    3. use App\Entity\BlogPost;
    4. return static function (ContainerConfigurator $container) {
    5. $container->parameters()
    6. // the parameter name is an arbitrary string (the 'app.' prefix is recommended
    7. // to better differentiate your parameters from Symfony parameters).
    8. ->set('app.admin_email', '[email protected]')
    9. // boolean parameters
    10. ->set('app.enable_v2_protocol', true)
    11. // array/collection parameters
    12. ->set('app.supported_locales', ['en', 'es', 'fr'])
    13. // binary content parameters (use the PHP escape sequences)
    14. ->set('app.some_parameter', 'This is a Bell char: \x07')
    15. // PHP constants as parameter values
    16. ->set('app.some_constant', GLOBAL_CONSTANT)
    17. ->set('app.another_constant', BlogPost::MAX_ITEMS);
    18. };
    19. // ...

Caution

When using XML configuration, the values between <parameter> tags are not trimmed. This means that the value of the following parameter will be '\n something@example.com\n':

  1. <parameter key="app.admin_email">
  2. [email protected]
  3. </parameter>

Once defined, you can reference this parameter value from any other configuration file using a special syntax: wrap the parameter name in two % (e.g. %app.admin_email%):

  • YAML

    1. # config/packages/some_package.yaml
    2. some_package:
    3. # any string surrounded by two % is replaced by that parameter value
    4. email_address: '%app.admin_email%'
    5. # ...
  • XML

    1. <!-- config/packages/some_package.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <container xmlns="http://symfony.com/schema/dic/services"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xmlns:framework="http://symfony.com/schema/dic/symfony"
    6. xsi:schemaLocation="http://symfony.com/schema/dic/services
    7. https://symfony.com/schema/dic/services/services-1.0.xsd
    8. http://symfony.com/schema/dic/symfony
    9. https://symfony.com/schema/dic/symfony/symfony-1.0.xsd">
    10. <!-- any string surrounded by two % is replaced by that parameter value -->
    11. <some-package:config email-address="%app.admin_email%">
    12. <!-- ... -->
    13. </some-package:config>
    14. </container>
  • PHP

    1. // config/packages/some_package.php
    2. namespace Symfony\Component\DependencyInjection\Loader\Configurator;
    3. return static function (ContainerConfigurator $container) {
    4. $container->extension('some_package', [
    5. // any string surrounded by two % is replaced by that parameter value
    6. 'email_address' => '%app.admin_email%',
    7. // ...
    8. ]);
    9. };

Note

If some parameter value includes the % character, you need to escape it by adding another % so Symfony doesn’t consider it a reference to a parameter name:

  • YAML

    1. # config/services.yaml
    2. parameters:
    3. # Parsed as 'https://symfony.com/?foo=%s&amp;bar=%d'
    4. url_pattern: 'https://symfony.com/?foo=%%s&amp;bar=%%d'
  • XML

    1. <!-- config/services.xml -->
    2. <parameters>
    3. <parameter key="url_pattern">http://symfony.com/?foo=%%s&amp;bar=%%d</parameter>
    4. </parameters>
  • PHP

    1. // config/services.php
    2. namespace Symfony\Component\DependencyInjection\Loader\Configurator;
    3. return static function (ContainerConfigurator $container) {
    4. $container->parameters()
    5. ->set('url_pattern', 'http://symfony.com/?foo=%%s&amp;bar=%%d');
    6. };

Note

Due to the way in which parameters are resolved, you cannot use them to build paths in imports dynamically. This means that something like the following doesn’t work:

  • YAML

    1. # config/services.yaml
    2. imports:
    3. - { resource: '%kernel.project_dir%/somefile.yaml' }
  • XML

    1. <!-- config/services.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <container xmlns="http://symfony.com/schema/dic/services"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xsi:schemaLocation="http://symfony.com/schema/dic/services
    6. https://symfony.com/schema/dic/services/services-1.0.xsd">
    7. <imports>
    8. <import resource="%kernel.project_dir%/somefile.yaml"/>
    9. </imports>
    10. </container>
  • PHP

    1. // config/services.php
    2. $loader->import('%kernel.project_dir%/somefile.yaml');

Configuration parameters are very common in Symfony applications. Some packages even define their own parameters (e.g. when installing the translation package, a new locale parameter is added to the config/services.yaml file).

See also

Later in this article you can read how to get configuration parameters in controllers and services.

Configuration Environments

You have only one application, but whether you realize it or not, you need it to behave differently at different times:

  • While developing, you want to log everything and expose nice debugging tools;
  • After deploying to production, you want that same application to be optimized for speed and only log errors.

The files stored in config/packages/ are used by Symfony to configure the application services. In other words, you can change the application behavior by changing which configuration files are loaded. That’s the idea of Symfony’s configuration environments.

A typical Symfony application begins with three environments: dev (for local development), prod (for production servers) and test (for automated tests). When running the application, Symfony loads the configuration files in this order (the last files can override the values set in the previous ones):

  1. config/packages/*.yaml (and *.xml and *.php files too);
  2. config/packages/<environment-name>/*.yaml (and *.xml and *.php files too);
  3. config/services.yaml (and services.xml and services.php files too);
  4. config/services_<environment-name>.yaml (and services_<environment-name>.xml and services_<environment-name>.php files too).

Take the framework package, installed by default, as an example:

  • First, config/packages/framework.yaml is loaded in all environments and it configures the framework with some options;
  • In the prod environment, nothing extra will be set as there is no config/packages/prod/framework.yaml file;
  • In the dev environment, there is no file either ( config/packages/dev/framework.yaml does not exist).
  • In the test environment, the config/packages/test/framework.yaml file is loaded to override some of the settings previously configured in config/packages/framework.yaml.

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.

See also

See the `configureContainer() method of the Kernel class to learn everything about the loading order of configuration files.

Selecting the Active Environment

Symfony applications come with a file called .env located at the project root directory. This file is used to define the value of environment variables and it’s explained in detail later in this article.

Open the .env file (or better, the .env.local file if you created one) and edit the value of the APP_ENV variable to change the environment in which the application runs. For example, to run the application in production:

  1. # .env (or .env.local)
  2. APP_ENV=prod

This value is used both for the web and for the console commands. However, you can override it for commands by setting the APP_ENV value before running them:

  1. # Use the environment defined in the .env file
  2. $ php bin/console command_name
  3. # Ignore the .env file and run this command in production
  4. $ APP_ENV=prod php bin/console command_name

Creating a New Environment

The default three environments provided by Symfony are enough for most projects, but you can define your own environments too. For example, this is how you can define a staging environment where the client can test the project before going to production:

  1. Create a configuration directory with the same name as the environment (in this case, config/packages/staging/);
  2. Add the needed configuration files in config/packages/staging/ to define the behavior of the new environment. Symfony loads the config/packages/*.yaml files first, so you only need to configure the differences to those files;
  3. Select the staging environment using the APP_ENV env var as explained in the previous section.

Tip

It’s common for environments to be similar to each other, so you can use symbolic links between config/packages/<environment-name>/ directories to reuse the same configuration.

Configuration Based on Environment Variables

Using environment variables (or “env vars” for short) is a common practice to configure options that depend on where the application is run (e.g. the database credentials are usually different in production versus your local machine). If the values are sensitive, you can even encrypt them as secrets.

You can reference environment variables using the special syntax %env(ENV_VAR_NAME)%. The values of these options are resolved at runtime (only once per request, to not impact performance).

This example shows how you could configure the database connection using an env var:

  • YAML

    1. # config/packages/doctrine.yaml
    2. doctrine:
    3. dbal:
    4. # by convention the env var names are always uppercase
    5. url: '%env(resolve:DATABASE_URL)%'
    6. # ...
  • XML

    1. <!-- config/packages/doctrine.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <container xmlns="http://symfony.com/schema/dic/services"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xmlns:doctrine="http://symfony.com/schema/dic/doctrine"
    6. xsi:schemaLocation="http://symfony.com/schema/dic/services
    7. https://symfony.com/schema/dic/services/services-1.0.xsd
    8. http://symfony.com/schema/dic/doctrine
    9. https://symfony.com/schema/dic/doctrine/doctrine-1.0.xsd">
    10. <doctrine:config>
    11. <!-- by convention the env var names are always uppercase -->
    12. <doctrine:dbal url="%env(resolve:DATABASE_URL)%"/>
    13. </doctrine:config>
    14. </container>
  • PHP

    1. // config/packages/doctrine.php
    2. namespace Symfony\Component\DependencyInjection\Loader\Configurator;
    3. return static function (ContainerConfigurator $container) {
    4. $container->extension('doctrine', [
    5. 'dbal' => [
    6. // by convention the env var names are always uppercase
    7. 'url' => '%env(resolve:DATABASE_URL)%',
    8. ]
    9. ]);
    10. };

See also

The values of env vars can only be strings, but Symfony includes some env var processors to transform their contents (e.g. to turn a string value into an integer).

To define the value of an env var, you have several options:

Tip

Some hosts - like SymfonyCloud - offer easy utilities to manage env vars in production.

Caution

Beware that dumping the contents of the $_SERVER and $_ENV variables or outputting the `phpinfo() contents will display the values of the environment variables, exposing sensitive information such as the database credentials.

The values of the env vars are also exposed in the web interface of the Symfony profiler. In practice this shouldn’t be a problem because the web profiler must never be enabled in production.

Configuring Environment Variables in .env Files

Instead of defining env vars in your shell or your web server, Symfony provides a convenient way to define them inside a .env (with a leading dot) file located at the root of your project.

The .env file is read and parsed on every request and its env vars are added to the $_ENV & $_SERVER PHP variables. Any existing env vars are never overwritten by the values defined in .env, so you can combine both.

For example, to define the DATABASE_URL env var shown earlier in this article, you can add:

  1. # .env
  2. DATABASE_URL="mysql://db_user:[email protected]:3306/db_name"

This file should be committed to your repository and (due to that fact) should only contain “default” values that are good for local development. This file should not contain production values.

In addition to your own env vars, this .env file also contains the env vars defined by the third-party packages installed in your application (they are added automatically by Symfony Flex when installing packages).

.env File Syntax

Add comments by prefixing them with #:

  1. # database credentials
  2. DB_USER=root
  3. DB_PASS=pass # this is the secret password

Use environment variables in values by prefixing variables with $:

  1. DB_USER=root
  2. DB_PASS=${DB_USER}pass # include the user as a password prefix

Caution

The order is important when some env var depends on the value of other env vars. In the above example, DB_PASS must be defined after DB_USER. Moreover, if you define multiple .env files and put DB_PASS first, its value will depend on the DB_USER value defined in other files instead of the value defined in this file.

Define a default value in case the environment variable is not set:

  1. DB_USER=
  2. DB_PASS=${DB_USER:-root}pass # results in DB_PASS=rootpass

New in version 4.4: The support for default values has been introduced in Symfony 4.4.

Embed commands via `$() (not supported on Windows):

  1. START_TIME=$(date)

Caution

Using `$() might not work depending on your shell.

Tip

As a .env file is a regular shell script, you can source it in your own shell scripts:

  1. $ source .env

Overriding Environment Values via .env.local

If you need to override an environment value (e.g. to a different value on your local machine), you can do that in a .env.local file:

  1. # .env.local
  2. DATABASE_URL="mysql://root:@127.0.0.1:3306/my_database_name"

This file should be ignored by git and should not be committed to your repository. Several other .env files are available to set environment variables in just the right situation:

  • .env: defines the default values of the env vars needed by the application;
  • .env.local: overrides the default values for all environments but only on the machine which contains the file. This file should not be committed to the repository and it’s ignored in the test environment (because tests should produce the same results for everyone);
  • .env.<environment> (e.g. .env.test): overrides env vars only for one environment but for all machines (these files are committed);
  • .env.<environment>.local (e.g. .env.test.local): defines machine-specific env var overrides only for one environment. It’s similar to .env.local, but the overrides only apply to one environment.

Real environment variables always win over env vars created by any of the .env files.

The .env and .env.<environment> files should be committed to the repository because they are the same for all developers and machines. However, the env files ending in .local (.env.local and .env.<environment>.local) should not be committed because only you will use them. In fact, the .gitignore file that comes with Symfony prevents them from being committed.

Caution

Applications created before November 2018 had a slightly different system, involving a .env.dist file. For information about upgrading, see: Nov 2018 Changes to .env & How to Update.

Configuring Environment Variables in Production

In production, the .env files are also parsed and loaded on each request. So the easiest way to define env vars is by deploying a .env.local file to your production server(s) with your production values.

To improve performance, you can optionally run the dump-env command (available in Symfony Flex 1.2 or later):

  1. # parses ALL .env files and dumps their final values to .env.local.php
  2. $ composer dump-env prod

After running this command, Symfony will load the .env.local.php file to get the environment variables and will not spend time parsing the .env files.

Tip

Update your deployment tools/workflow to run the dump-env command after each deploy to improve the application performance.

Encrypting Environment Variables (Secrets)

Instead of defining a real environment variable or adding it to a .env file, if the value of a variable is sensitive (e.g. an API key or a database password), you can encrypt the value using the secrets management system.

Listing Environment Variables

Regardless of how you set environment variables, you can see a full list with their values by running:

  1. $ php bin/console debug:container --env-vars
  2. ---------------- ----------------- ---------------------------------------------
  3. Name Default value Real value
  4. ---------------- ----------------- ---------------------------------------------
  5. APP_SECRET n/a "471a62e2d601a8952deb186e44186cb3"
  6. FOO "[1, "2.5", 3]" n/a
  7. BAR null n/a
  8. ---------------- ----------------- ---------------------------------------------
  9. # you can also filter the list of env vars by name:
  10. $ php bin/console debug:container --env-vars foo
  11. # run this command to show all the details for a specific env var:
  12. $ php bin/console debug:container --env-var=FOO

New in version 4.3: The option to debug environment variables was introduced in Symfony 4.3.

Accessing Configuration Parameters

Controllers and services can access all the configuration parameters. This includes both the parameters defined by yourself and the parameters created by packages/bundles. Run the following command to see all the parameters that exist in your application:

  1. $ php bin/console debug:container --parameters

In controllers extending from the AbstractController, use the `getParameter() helper:

  1. // src/Controller/UserController.php
  2. namespace App\Controller;
  3. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  4. use Symfony\Component\HttpFoundation\Response;
  5. class UserController extends AbstractController
  6. {
  7. // ...
  8. public function index(): Response
  9. {
  10. $projectDir = $this->getParameter('kernel.project_dir');
  11. $adminEmail = $this->getParameter('app.admin_email');
  12. // ...
  13. }
  14. }

In services and controllers not extending from AbstractController, inject the parameters as arguments of their constructors. You must inject them explicitly because service autowiring doesn’t work for parameters:

  • YAML

    1. # config/services.yaml
    2. parameters:
    3. app.contents_dir: '...'
    4. services:
    5. App\Service\MessageGenerator:
    6. arguments:
    7. $contentsDir: '%app.contents_dir%'
  • XML

    1. <!-- config/services.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <container xmlns="http://symfony.com/schema/dic/services"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xsi:schemaLocation="http://symfony.com/schema/dic/services
    6. https://symfony.com/schema/dic/services/services-1.0.xsd">
    7. <parameters>
    8. <parameter key="app.contents_dir">...</parameter>
    9. </parameters>
    10. <services>
    11. <service id="App\Service\MessageGenerator">
    12. <argument key="$contentsDir">%app.contents_dir%</argument>
    13. </service>
    14. </services>
    15. </container>
  • PHP

    1. // config/services.php
    2. namespace Symfony\Component\DependencyInjection\Loader\Configurator;
    3. use App\Service\MessageGenerator;
    4. return static function (ContainerConfigurator $container) {
    5. $container->parameters()
    6. ->set('app.contents_dir', '...');
    7. $container->services()
    8. ->get(MessageGenerator::class)
    9. ->arg('$contentsDir', '%app.contents_dir%');
    10. };

If you inject the same parameters over and over again, use the services._defaults.bind option instead. The arguments defined in that option are injected automatically whenever a service constructor or controller action defines an argument with that exact name. For example, to inject the value of the kernel.project_dir parameter whenever a service/controller defines a $projectDir argument, use this:

  • YAML

    1. # config/services.yaml
    2. services:
    3. _defaults:
    4. bind:
    5. # pass this value to any $projectDir argument for any service
    6. # that's created in this file (including controller arguments)
    7. $projectDir: '%kernel.project_dir%'
    8. # ...
  • XML

    1. <!-- config/services.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <container xmlns="http://symfony.com/schema/dic/services"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xsi:schemaLocation="http://symfony.com/schema/dic/services
    6. https://symfony.com/schema/dic/services/services-1.0.xsd">
    7. <services>
    8. <defaults autowire="true" autoconfigure="true" public="false">
    9. <!-- pass this value to any $projectDir argument for any service
    10. that's created in this file (including controller arguments) -->
    11. <bind key="$projectDir">%kernel.project_dir%</bind>
    12. </defaults>
    13. <!-- ... -->
    14. </services>
    15. </container>
  • PHP

    1. // config/services.php
    2. namespace Symfony\Component\DependencyInjection\Loader\Configurator;
    3. use App\Controller\LuckyController;
    4. return static function (ContainerConfigurator $container) {
    5. $container->services()
    6. ->defaults()
    7. // pass this value to any $projectDir argument for any service
    8. // that's created in this file (including controller arguments)
    9. ->bind('$projectDir', '%kernel.project_dir%');
    10. // ...
    11. };

See also

Read the article about binding arguments by name and/or type to learn more about this powerful feature.

Finally, if some service needs access to lots of parameters, instead of injecting each of them individually, you can inject all the application parameters at once by type-hinting any of its constructor arguments with the Symfony\Component\DependencyInjection\ParameterBag\ContainerBagInterface:

  1. // src/Service/MessageGenerator.php
  2. namespace App\Service;
  3. // ...
  4. use Symfony\Component\DependencyInjection\ParameterBag\ContainerBagInterface;
  5. class MessageGenerator
  6. {
  7. private $params;
  8. public function __construct(ContainerBagInterface $params)
  9. {
  10. $this->params = $params;
  11. }
  12. public function someMethod()
  13. {
  14. // get any container parameter from $this->params, which stores all of them
  15. $sender = $this->params->get('mailer_sender');
  16. // ...
  17. }
  18. }

Keep Going!

Congratulations! You’ve tackled the basics of Symfony. Next, learn about each part of Symfony individually by following the guides. Check out:

And all the other topics related to configuration:

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.