How can I retrieve my environment variables in a parameter file in Symfony4 structure?

后端 未结 2 1207
失恋的感觉
失恋的感觉 2021-01-11 18:03

I did a fresh Symfony installation by using Symfony Flex and the new skeleton belong to the next Symfony 4 directory structure.

I add and configure a first third-pa

相关标签:
2条回答
  • 2021-01-11 18:10

    You need to load the .env file during your bootstrap process, in order for those environment variables to be available:

    (new DotEnv())->load(__DIR__ . '/../.env');
    

    You should plan to put secret keys in environment variables on development, staging, and production. How you do that depends, though. In development and staging, perhaps you use .env files, while on production you use Apache to inject.

    Personally, I always use .env files, and I keep a blank one in my repository. That way it's super simple to deploy, and there aren't any special cases.

    If you only want to use .env files in specific environments, you can do:

    if (in_array(getenv('APP_ENV'), [ 'dev', 'test' ])) {
        (new DotEnv())->load(__DIR__ . '/../.env');
    }
    
    0 讨论(0)
  • 2021-01-11 18:24

    For test environments I'd suggest also create a bootstrap.php script to override the .env parameters:

    tests/bootstrap.php:

    <?php
    
    use Symfony\Component\Dotenv\Dotenv;
    
    require_once __DIR__.'/../vendor/autoload.php';
    
    $dotEnv = new Dotenv();
    $dotEnv->load(__DIR__.'/../.env');
    $dotEnv->populate([
        'APP_ENV' => 'test',
        'DATABASE_URL' => '...'
        // ...
    ]);
    

    phpunit.xml.dist:

    <?xml version="1.0" encoding="UTF-8"?>
    
    <phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
             bootstrap="tests/bootstrap.php" <--- set
             ...
    >
        ...
    </phpunit>
    
    0 讨论(0)
提交回复
热议问题