patternphpMinor
PHP Configuration class
Viewed 0 times
phpconfigurationclass
Problem
Created this little config class, any room for improvements? Think I have done an alright job but would like to know if any improovements could be made?
setConfig(explode("=", $line)[0], explode("=", $line)[1]);
}
private function loadDefault()
{
/* DEFAULT CONFIG SETTINGS!!
THIS SHOULD NOT BE THE CASE... */
setConfig("database.host", "localhost");
setConfig("database.username", "root");
setConfig("database.password", "");
setConfig("database.title", "mydb");
setConfig("database.port", "3306");
}
private function setConfig($name, $value)
{
$this->configVlaues[$name] = $value;
}
public function getConfig($name)
{
return $this->configValues[$name];
}
}
?>Solution
Things that just pop up in my mind when seeing the code (more of the architecture and robustness rather than language constructs):
1) Harcoding path to ini file
The path might have a meaning in your development environment, but it will mean nothing in a test or production environment. I would set it in an included file and use it from there. Something like:
in
$configFile = !isset($configFile) ? $defaultConfigFilePath : $configFile;
Hopefully, they will introduce a coalesce operator soon to simply write:
2) Error handling
You can explode into an
3) A more powerful config reader
This is a good exercise, but ini files have a more complex format that seems to be handled by parse_ini_file function.
1) Harcoding path to ini file
The path might have a meaning in your development environment, but it will mean nothing in a test or production environment. I would set it in an included file and use it from there. Something like:
$defaultConfigFilePath = "C:\Users\ashle\Miracle\config\config.ini";in
loadConfiguration$configFile = !isset($configFile) ? $defaultConfigFilePath : $configFile;
Hopefully, they will introduce a coalesce operator soon to simply write:
$configFile = $configFile ?? $defaultConfigFilePath;2) Error handling
loadConfiguration function does not handle any incorrect formatting. Any line which is not in the format name=value will not be imported correctly.You can explode into an
$lineArray and check if elements are defined and exactly two.3) A more powerful config reader
This is a good exercise, but ini files have a more complex format that seems to be handled by parse_ini_file function.
Code Snippets
$defaultConfigFilePath = "C:\Users\ashle\Miracle\config\config.ini";$configFile = $configFile ?? $defaultConfigFilePath;Context
StackExchange Code Review Q#120603, answer score: 3
Revisions (0)
No revisions yet.