phpyii2yii-extensionsyii2-basic-app

How to create environment variables with the the package vlucas/phpdotenv with yii2 basic template?


I am using yii 2 basic template. And I try to generate different environments. Like: dev, test, prod.

So I installed the package

"vlucas/phpdotenv": "^5.6"

And in the root folder I created an .env file with content:

YII_DEBUG=1
YII_ENV=dev

DB_HOST=localhost
DB_NAME=name
DB_USER=postgres
DB_PASSWORD=pass
DB_CHARSET=utf8

and in config/db.php I have this:


<?php

// phpcs:ignoreFile


$config = [
    'class' => 'yii\db\Connection',
    'dsn' => 'mysql:host=' . $_ENV['DB_HOST'] .';dbname=' . $_ENV['DB_NAME'],
    'username' => $_ENV['DB_USER'],
    'password' => $_ENV['DB_PASSWORD'],
    'charset' => $_ENV['DB_CHARSET'],
   
];

and my web/index.php looks:

<?php

defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');

require __DIR__ . '/../vendor/autoload.php';
require __DIR__ . '/../vendor/yiisoft/yii2/Yii.php';

$dotenv = Dotenv\Dotenv::createImmutable(dirname(__DIR__));
$dotenv->load();

$config = require __DIR__ . '/../config/web.php';

(new yii\web\Application($config))->run();

but if I do now php yii serve. I get this error:

Warning: Undefined array key "DB_HOST" in C:\repos\internet_backend\config\db.php on line 9
PHP Warning:  Undefined array key "DB_NAME" in C:\repos\internet_backend\config\db.php on line 9

Warning: Undefined array key "DB_NAME" in C:\repos\internetsuite_backend\config\db.php on line 9
PHP Warning:  Undefined array key "DB_USER" in C:\repos\internet_backend\config\db.php on line 10

Warning: Undefined array key "DB_USER" in C:\repos\internet_backend\config\db.php on line 10
PHP Warning:  Undefined array key "DB_PASSWORD" in C:\repos\internet_backend\config\db.php on line 11

Question: But how to resolve this errors?


Solution

  • You need to use the Dotenv\Dotenv class to load your .env file. You should do that in your web/index.php file after the composer autoloader is loaded and before loading the config file.

    <?php
    
    // comment out the following two lines when deployed to production
    defined('YII_DEBUG') or define('YII_DEBUG', true);
    defined('YII_ENV') or define('YII_ENV', 'dev');
    
    require __DIR__ . '/../vendor/autoload.php';
    require __DIR__ . '/../vendor/yiisoft/yii2/Yii.php';
    
    $dotenv = Dotenv\Dotenv::createImmutable(dirname(__DIR__));
    $dotenv->load();
    
    $config = require __DIR__ . '/../config/web.php';
    
    (new yii\web\Application($config))->run();
    

    You might have to modify the yii file in the root of your project in similar way.

    Also, there shouldn't be spaces around = in .env file.