Skip to content
  • About
    • What is Symfony?
    • Community
    • News
    • Contributing
    • Support
  • Documentation
    • Symfony Docs
    • Symfony Book
    • Screencasts
    • Symfony Bundles
    • Symfony Cloud
    • Training
  • Services
    • SensioLabs Professional services to help you with Symfony
    • Platform.sh for Symfony Best platform to deploy Symfony apps
    • SymfonyInsight Automatic quality checks for your apps
    • Symfony Certification Prove your knowledge and boost your career
    • Blackfire Profile and monitor performance of your apps
  • Other
  • Blog
  • Download
sponsored by SensioLabs
  1. Home
  2. Documentation
  3. Configuration
  4. How to Set external Parameters in the Service Container
  • Documentation
  • Book
  • Reference
  • Bundles
  • Cloud

Table of Contents

  • Environment Variables
    • Configuring Environment Variables in Production
  • Environment Variable Processors
    • Custom Environment Variable Processors
  • Constants
  • Miscellaneous Configuration

How to Set external Parameters in the Service Container

Edit this page

Warning: You are browsing the documentation for Symfony 4.0, which is no longer maintained.

Read the updated version of this page for Symfony 6.2 (the current stable version).

How to Set external Parameters in the Service Container

In Configuring Symfony (and Environments), you learned how to manage your application configuration. At times, it may benefit your application to store certain credentials outside of your project code. Database configuration is one such example. The flexibility of the Symfony service container allows you to easily do this.

Environment Variables

You can reference environment variables by using special parameters named after the variables you want to use enclosed between env(). Their actual values will be resolved at runtime (once per request), so that dumped containers can be reconfigured dynamically even after being compiled.

For example, when installing the doctrine recipe, database configuration is put in a DATABASE_URL environment variable:

1
2
# .env
DATABASE_URL="mysql://db_user:db_password@127.0.0.1:3306/db_name"

This variable is referenced in the service container configuration using %env(DATABASE_URL)%:

  • YAML
  • XML
  • PHP
1
2
3
4
5
# config/packages/doctrine.yaml
doctrine:
    dbal:
        url: '%env(DATABASE_URL)%'
    # ...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<!-- config/packages/doctrine.xml -->
<?xml version="1.0" encoding="UTF-8" ?>
<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:doctrine="http://symfony.com/schema/dic/doctrine"
    xsi:schemaLocation="http://symfony.com/schema/dic/services
        http://symfony.com/schema/dic/services/services-1.0.xsd
        http://symfony.com/schema/dic/doctrine
        http://symfony.com/schema/dic/doctrine/doctrine-1.0.xsd">

    <doctrine:config>
        <doctrine:dbal
            url="%env(DATABASE_URL)%"
        />
    </doctrine:config>

</container>
1
2
3
4
5
6
// config/packages/doctrine.php
$container->loadFromExtension('doctrine', array(
    'dbal' => array(
        'url' => '%env(DATABASE_URL)%',
    )
));

You can also give the env() parameters a default value: the default value will be used whenever the corresponding environment variable is not found:

  • YAML
  • XML
  • PHP
1
2
3
# config/services.yaml
parameters:
    env(DATABASE_HOST): localhost
1
2
3
4
5
6
7
8
9
10
<!-- config/services.xml -->
<?xml version="1.0" encoding="UTF-8" ?>
<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

    <parameters>
        <parameter key="env(DATABASE_HOST)">localhost</parameter>
    </parameters>
 </container>
1
2
// config/services.php
$container->setParameter('env(DATABASE_HOST)', 'localhost');

Configuring Environment Variables in Production

During development, you'll use the .env file to configure your environment variables. On your production server, it is recommended to configure these at the web server level. If you're using Apache or Nginx, you can use e.g. one of the following:

  • Apache
  • Nginx
1
2
3
4
5
<VirtualHost *:80>
    # ...

    SetEnv DATABASE_URL "mysql://db_user:db_password@127.0.0.1:3306/db_name"
</VirtualHost>
1
fastcgi_param DATABASE_URL "mysql://db_user:db_password@127.0.0.1:3306/db_name";

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.

Environment Variable Processors

3.4

Environment variable processors were introduced in Symfony 3.4.

The values of environment variables are considered strings by default. However, your code may expect other data types, like integers or booleans. Symfony solves this problem with processors, which modify the contents of the given environment variables. The following example uses the integer processor to turn the value of the HTTP_PORT env var into an integer:

  • YAML
  • XML
  • PHP
1
2
3
4
# config/packages/framework.yaml
framework:
    router:
        http_port: env(int:HTTP_PORT)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!-- config/packages/framework.xml -->
<?xml version="1.0" encoding="UTF-8" ?>
<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:framework="http://symfony.com/schema/dic/symfony"
    xsi:schemaLocation="http://symfony.com/schema/dic/services
        http://symfony.com/schema/dic/services/services-1.0.xsd
        http://symfony.com/schema/dic/symfony
        http://symfony.com/schema/dic/symfony/symfony-1.0.xsd">

    <framework:config>
        <framework:router http-port="%env(int:HTTP_PORT)%" />
    </framework:config>
</container>
1
2
3
4
5
6
// config/packages/framework.php
$container->loadFromExtension('framework', array(
    'router' => array(
        'http_port' => '%env(int:HTTP_PORT)%',
    ),
));

Symfony provides the following env var processors:

env(string:FOO)

Casts FOO to a string:

  • YAML
  • XML
  • PHP
1
2
3
4
5
# config/packages/framework.yaml
parameters:
    env(SECRET): 'some_secret'
framework:
   secret: '%env(string:SECRET)%'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!-- config/packages/framework.xml -->
<?xml version="1.0" encoding="UTF-8" ?>
<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:framework="http://symfony.com/schema/dic/symfony"
    xsi:schemaLocation="http://symfony.com/schema/dic/services
        http://symfony.com/schema/dic/services/services-1.0.xsd
        http://symfony.com/schema/dic/symfony
        http://symfony.com/schema/dic/symfony/symfony-1.0.xsd">

    <parameters>
        <parameter key="env(SECRET)">some_secret</parameter>
    </parameters>

    <framework:config secret="%env(string:SECRET)%" />
</container>
1
2
3
4
5
// config/packages/framework.php
$container->setParameter('env(SECRET)', 'some_secret');
$container->loadFromExtension('framework', array(
    'secret' => '%env(string:SECRET)%',
));
env(bool:FOO)

Casts FOO to a bool:

  • YAML
  • XML
  • PHP
1
2
3
4
5
# config/packages/framework.yaml
parameters:
    env(HTTP_METHOD_OVERRIDE): 'true'
framework:
   http_method_override: '%env(bool:HTTP_METHOD_OVERRIDE)%'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!-- config/packages/framework.xml -->
<?xml version="1.0" encoding="UTF-8" ?>
<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:framework="http://symfony.com/schema/dic/symfony"
    xsi:schemaLocation="http://symfony.com/schema/dic/services
        http://symfony.com/schema/dic/services/services-1.0.xsd
        http://symfony.com/schema/dic/symfony
        http://symfony.com/schema/dic/symfony/symfony-1.0.xsd">

    <parameters>
        <parameter key="env(HTTP_METHOD_OVERRIDE)">true</parameter>
    </parameters>

    <framework:config http-methode-override="%env(bool:HTTP_METHOD_OVERRIDE)%" />
</container>
1
2
3
4
5
// config/packages/framework.php
$container->setParameter('env(HTTP_METHOD_OVERRIDE)', 'true');
$container->loadFromExtension('framework', array(
    'http_method_override' => '%env(bool:HTTP_METHOD_OVERRIDE)%',
));
env(int:FOO)
Casts FOO to an int.
env(float:FOO)
Casts FOO to a float.
env(const:FOO)

Finds the const value named in FOO:

  • YAML
  • XML
  • PHP
1
2
3
4
5
6
# config/packages/security.yaml
parameters:
    env(HEALTH_CHECK_METHOD): 'Symfony\Component\HttpFoundation\Request::METHOD_HEAD'
security:
   access_control:
     - { path: '^/health-check$', methods: '%env(const:HEALTH_CHECK_METHOD)%' }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!-- config/packages/security.xml -->
<?xml version="1.0" encoding="UTF-8" ?>
<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:security="http://symfony.com/schema/dic/security"
    xsi:schemaLocation="http://symfony.com/schema/dic/services
        http://symfony.com/schema/dic/services/services-1.0.xsd">

    <parameters>
        <parameter key="env(HEALTH_CHECK_METHOD)">Symfony\Component\HttpFoundation\Request::METHOD_HEAD</parameter>
    </parameters>

    <security:config>
        <rule path="^/health-check$" methods="%env(const:HEALTH_CHECK_METHOD)%" />
    </security:config>
</container>
1
2
3
4
5
6
7
8
9
10
// config/packages/security.php
$container->setParameter('env(HEALTH_CHECK_METHOD)', 'Symfony\Component\HttpFoundation\Request::METHOD_HEAD');
$container->loadFromExtension('security', array(
    'access_control' => array(
        array(
            'path' => '^/health-check$',
            'methods' => '%env(const:HEALTH_CHECK_METHOD)%',
        ),
    ),
));
env(base64:FOO)
Decodes the content of FOO, which is a base64 encoded string.
env(json:FOO)

Decodes the content of FOO, which is a JSON encoded string. It returns either an array or null:

  • YAML
  • XML
  • PHP
1
2
3
4
5
# config/packages/framework.yaml
parameters:
    env(TRUSTED_HOSTS): '["10.0.0.1", "10.0.0.2"]'
framework:
   trusted_hosts: '%env(json:TRUSTED_HOSTS)%'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!-- config/packages/framework.xml -->
<?xml version="1.0" encoding="UTF-8" ?>
<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:framework="http://symfony.com/schema/dic/symfony"
    xsi:schemaLocation="http://symfony.com/schema/dic/services
        http://symfony.com/schema/dic/services/services-1.0.xsd
        http://symfony.com/schema/dic/symfony
        http://symfony.com/schema/dic/symfony/symfony-1.0.xsd">

    <parameters>
        <parameter key="env(TRUSTED_HOSTS)">["10.0.0.1", "10.0.0.2"]</parameter>
    </parameters>

    <framework:config trusted-hosts="%env(json:TRUSTED_HOSTS)%" />
</container>
1
2
3
4
5
// config/packages/framework.php
$container->setParameter('env(TRUSTED_HOSTS)', '["10.0.0.1", "10.0.0.2"]');
$container->loadFromExtension('framework', array(
    'trusted_hosts' => '%env(json:TRUSTED_HOSTS)%',
));
env(resolve:FOO)

Replaces the string FOO by the value of a config parameter with the same name:

  • YAML
  • XML
  • PHP
1
2
3
4
5
6
# config/packages/sentry.yaml
parameters:
    env(HOST): '10.0.0.1'
    env(SENTRY_DSN): 'http://%env(HOST)%/project'
sentry:
    dsn: '%env(resolve:SENTRY_DSN)%'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!-- config/packages/sentry.xml -->
<?xml version="1.0" encoding="UTF-8" ?>
<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services
        http://symfony.com/schema/dic/services/services-1.0.xsd">

    <parameters>
        <parameter key="env(HOST)">10.0.0.1</parameter>
        <parameter key="env(SENTRY_DSN)">http://%env(HOST)%/project</parameter>
    </parameters>

    <sentry:config dsn="%env(resolve:SENTRY_DSN)%" />
</container>
1
2
3
4
5
6
// config/packages/sentry.php
$container->setParameter('env(HOST)', '10.0.0.1');
$container->setParameter('env(SENTRY_DSN)', 'http://%env(HOST)%/project');
$container->loadFromExtension('sentry', array(
    'dsn' => '%env(resolve:SENTRY_DSN)%',
));
env(file:FOO)

Returns the contents of a file whose path is the value of the FOO env var:

  • YAML
  • XML
  • PHP
1
2
3
4
5
# config/packages/framework.yaml
parameters:
    env(AUTH_FILE): '../config/auth.json'
google:
    auth: '%env(file:AUTH_FILE)%'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!-- config/packages/framework.xml -->
<?xml version="1.0" encoding="UTF-8" ?>
<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:framework="http://symfony.com/schema/dic/symfony"
    xsi:schemaLocation="http://symfony.com/schema/dic/services
        http://symfony.com/schema/dic/services/services-1.0.xsd
        http://symfony.com/schema/dic/symfony
        http://symfony.com/schema/dic/symfony/symfony-1.0.xsd">

    <parameters>
        <parameter key="env(AUTH_FILE)">../config/auth.json</parameter>
    </parameters>

    <google auth="%env(file:AUTH_FILE)%" />
</container>
1
2
3
4
5
// config/packages/framework.php
$container->setParameter('env(AUTH_FILE)', '../config/auth.json');
$container->loadFromExtension('google', array(
    'auth' => '%env(file:AUTH_FILE)%',
));

It is also possible to combine any number of processors:

1
2
3
4
5
6
7
8
parameters:
    env(AUTH_FILE): "%kernel.project_dir%/config/auth.json"
google:
    # 1. gets the value of the AUTH_FILE env var
    # 2. replaces the values of any config param to get the config path
    # 3. gets the content of the file stored in that path
    # 4. JSON-decodes the content of the file and returns it
    auth: '%env(json:file:resolve:AUTH_FILE)%'

Custom Environment Variable Processors

It's also possible to add your own processors for environment variables. First, create a class that implements EnvVarProcessorInterface and then, define a service for that class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class LowercasingEnvVarProcessor implements EnvVarProcessorInterface
{
    private $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    public function getEnv($prefix, $name, \Closure $getEnv)
    {
        $env = $getEnv($name);

        return strtolower($env);
    }

    public static function getProvidedTypes()
    {
        return [
            'lowercase' => 'string',
        ];
    }
}

Constants

The container also has support for setting PHP constants as parameters. See Introduction to Parameters for more details.

Miscellaneous Configuration

You can mix whatever configuration format you like (YAML, XML and PHP) in config/packages/. Importing a PHP file gives you the flexibility to add whatever is needed in the container. For instance, you can create a drupal.php file in which you set a database URL based on Drupal's database configuration:

1
2
3
4
5
6
7
// config/packages/drupal.php

// import Drupal's configuration
include_once('/path/to/drupal/sites/default/settings.php');

// set a app.database_url parameter
$container->setParameter('app.database_url', $db_url);
This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.
TOC
    Version
    We stand with Ukraine.
    Version:
    No stress: we've got you covered with our 116 automated quality checks of your code

    No stress: we've got you covered with our 116 automated quality checks of your code

    Measure & Improve Symfony Code Performance

    Measure & Improve Symfony Code Performance

    Symfony footer

    ↓ Our footer now uses the colors of the Ukrainian flag because Symfony stands with the people of Ukraine.

    Avatar of Jonathan Sui Lioung Lee Slew, a Symfony contributor

    Thanks Jonathan Sui Lioung Lee Slew (@jlslew) for being a Symfony contributor

    3 commits • 49 lines changed

    View all contributors that help us make Symfony

    Become a Symfony contributor

    Be an active part of the community and contribute ideas, code and bug fixes. Both experts and newcomers are welcome.

    Learn how to contribute

    Symfony™ is a trademark of Symfony SAS. All rights reserved.

    • What is Symfony?

      • Symfony at a Glance
      • Symfony Components
      • Case Studies
      • Symfony Releases
      • Security Policy
      • Logo & Screenshots
      • Trademark & Licenses
      • symfony1 Legacy
    • Learn Symfony

      • Symfony Docs
      • Symfony Book
      • Reference
      • Bundles
      • Best Practices
      • Training
      • eLearning Platform
      • Certification
    • Screencasts

      • Learn Symfony
      • Learn PHP
      • Learn JavaScript
      • Learn Drupal
      • Learn RESTful APIs
    • Community

      • SymfonyConnect
      • Support
      • How to be Involved
      • Code of Conduct
      • Events & Meetups
      • Projects using Symfony
      • Downloads Stats
      • Contributors
      • Backers
    • Blog

      • Events & Meetups
      • A week of symfony
      • Case studies
      • Cloud
      • Community
      • Conferences
      • Diversity
      • Documentation
      • Living on the edge
      • Releases
      • Security Advisories
      • SymfonyInsight
      • Twig
      • SensioLabs
    • Services

      • SensioLabs services
      • Train developers
      • Manage your project quality
      • Improve your project performance
      • Host Symfony projects

      Deployed on

    Follow Symfony

    Search by Algolia