patternphpMinor
Assigning database credentials
Viewed 0 times
databasecredentialsassigning
Problem
I have a config.ini that contains my database credentials. I retrieve them with a parser class like this:
In my
I'm sure there is a better way to set these values, but I'm not sure how.
public function getField($section, $field) {
return $this->iniArray[$section][$field];
}In my
DbConnect class I do this, which seems silly:public function __construct() {
$ini = new Configuration('configs/config.ini');
$this->host = $ini->getField('Database', 'host');
$this->user = $ini->getField('Database', 'user');
$this->pass = $ini->getField('Database', 'password');
$this->dbname = $ini->getField('Database', 'name');I'm sure there is a better way to set these values, but I'm not sure how.
Solution
Perhaps instead of an ini file, a JSON would suit the purpose better. I've seen this multiple times, even in large, well-known PHP frameworks.
You can find a lot about decoding JSON from the docs. Here's a little blog post about handling decoding. And here's a StackOverflow question regarding the external file.
Also, if you keep the same class, I suggest passing
You can find a lot about decoding JSON from the docs. Here's a little blog post about handling decoding. And here's a StackOverflow question regarding the external file.
Also, if you keep the same class, I suggest passing
Configuration through the constructor to practice dependency injection.public function __construct(Configuration $ini) {
$this->host = $ini->getField('Database', 'host');
$this->user = $ini->getField('Database', 'user');
$this->pass = $ini->getField('Database', 'password');
$this->dbname = $ini->getField('Database', 'name');
}Code Snippets
public function __construct(Configuration $ini) {
$this->host = $ini->getField('Database', 'host');
$this->user = $ini->getField('Database', 'user');
$this->pass = $ini->getField('Database', 'password');
$this->dbname = $ini->getField('Database', 'name');
}Context
StackExchange Code Review Q#64926, answer score: 2
Revisions (0)
No revisions yet.