Reputation: 171
I need to make some slight configuration changes in my local dev env. Thus, I would like to know what is the "best practice" in distinguishing between environments. I would like to have only one config file which will behave differently depending on which environment it is executed.
Upvotes: 2
Views: 758
Reputation: 3189
Common and good practice is to use different .env
files on different environments.
Basically, a
.env
file is an easy way to load custom configuration variables that your application needs without having to modify .htaccess files or Apache/Nginx virtual hosts. This means you won't have to edit any files outside the project, and all the environment variables are always set no matter how you run your project - Apache, Nginx, CLI, and even PHP 5.4's built-in webserver. It's WAY easier than all the other ways you know of to set environment variables, and you're going to love it.
You can use some already created packages to add this to your project. Check this one: https://github.com/vlucas/phpdotenv
Example (just for a demo, not production ready code!):
Note! You will need to add .env
to .gitignore
file to keep it not synced between environments.
Development .env
file:
DB_HOST=localhost
DB_USER=root
DB_PASSWORD=
Production .env
file:
DB_HOST=192.168.10.1
DB_USER=dbUser
DB_PASSWORD=123456
Possible config.php
file:
<?php
// add composer autoload somewhere here...
$dotenv = new Dotenv\Dotenv(__DIR__);
$dotenv->load();
return [
'db' => [
'host' => getenv('DB_HOST'),
'user' => getenv('DB_USER'),
'pass' => getenv('DB_PASSWORD'),
]
]
Upvotes: 2