2
Currently I use constants to store configuration data in my application, but searching saw that it is a "bad practice" by coupling that can generate, I found some questions right here in Stackoverflow saying that the best thing to do is to put all the settings in a file (.ini, .xml, etc) and create a class to recover these values.
1 - One of the "problems" I found is when I need to use these values in views/html. For example, when loading css/js, I currently do so:
<link rel="..." href="<?=APPURL?>/public/css/...">
in which case the use of constants is correct? even because this constant "APPURL" is generated outside the configuration file, within another class that generates the friendly url dynamically.
What I built to replace the use of constants was the following:
// interface para forçar implementações de qualquer configuração que eu faça
interface ConfigHandler {
function setConfigFile($file);
function getConfigFile($file);
function getConfigFileContent($file);
function get();
}
.
// classe que recupera as configurações de um json
class jsonConfig implements ConfigHandler {
private static $configFile = 'config.json';
static function setConfigFile ($configFile) {
if(isset($configFile) && is_readable($configFile))
self::$configFile = $configFile;
else
throw new Exception("Arquivo '$configFile' nao encontrado");
}
static function getConfigFileContent () {
return file_get_contents(self::$configFile);
}
static function getConfigFile () {
return self::$configFile;
}
static function get($param = null) {
$configs = json_decode(self::getConfigFileContent(), true);
if($param)
return $configs[$param];
return $configs;
}
}
.
// caso eu precise mudar pra um arquivo xml
class xmlConfig implements configHandler {...}
Example of use:
$host = jsonConfig::get('dbhost');
$user = jsonConfig::get('dbuser');
$pass = jsonConfig::get('dbpass');
$PDO = new PDO(...);
2 - In this case of the configuration classes, setting a constant outside the application with the file name to be read is also correct? otherwise if I wanted to change the file only by editing the class?