I want to make my project more scalable using docker and environment variables. I am using the latest version of CakePhp 2 and my project is also running well in docker. Now I want to create an .env file where information like the database name, database user, database password, Salt value and so on is stored and later on created by the configuration of the docker container. Creating the .env file and reading the values in CakePhp is easy. I created a file called .env and put it into the app folder. It is looking like
//.env in app folder
{
"DB_USER" : "user",
"DB_PASS" : "password"
}
Then I am putting the information from the .env file into the environment in the bootstrap.php using this function:
//bootstrap.php Putting env infos to the env from the .env file
if(is_file(APP . DS . '.env')) {
$vars = json_decode(file_get_contents(APP . DS . '.env'), true);
foreach ($vars as $name => $val) {
putenv("$name=$val");
}
}
Finally, I want to call the env information from the database.php
//database.php Get value from env
public $default = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => 'host.docker.internal',
'login' => env('DB_USER'),
'password' => env('DB_PASS'),
'database' => 'dbname',
'prefix' => '',
'encoding' => 'utf8',
);
Unluckily CakePhp does not wants the env() inside the array of the database.php and returns the message Fatal error: Constant expression contains invalid operations in /var/www/html/test/app/Config/database.php on line 70
. What can I do to use the .env file and call the environment information for e.g. the database configuration?
If I try to call the env values from somewhere else, I can fetch them without any problems.