When making a website, I have always just had a single config.php
file with a bunch of constants in it, and I include it at the top of every PHP file:
1. config.php
// config.php
$hostname = get_user();
define("HOME", "/home/$hostname/my/website");
define("DB_USER", 'username');
define("DB_PASS", 'password');
This is easy enough and I've never had a problem with it. But is this the standard way to handle config in a big PHP website?
I thought it might be better to contain all the config in a class, like this:
2. Config class
class Config {
public $home;
const DB_USER = 'username';
const DB_PASS = 'password';
function __construct() {
$hostname = get_current_user();
$this->home = "/home/$hostname/my/website";
}
}
But this seems to make the config more complex, because:
Summary.
I realize the class provides namespacing, but is there anything much more beneficial about putting config in to a class like this?
In short, is it still perfectly fine these days to stick to a classic config.php file, or are there reasons why I look toward using a more OOP approach to configuration?
EDIT:
I also found this answer very helpful: https://codereview.stackexchange.com/questions/79528/standard-and-common-config-file-for-core-php-project?newreg=eb97ce022c9f4e8a98a1e2d3547b767a
It's fine to use site wide config files. You would typically use a config class for library-specific configs so that a library only strictly accepts well defined config objects as its dependency instead of arrays. As a bonus, you get the added benefit of type hinting the config parameters.