So I did some research on good way of connecting to the database in OOP. If you look at my connect()
method in my database model, I am only connecting when I'm about to query and if there is no connection already. I think it's called lazy connecting, and I stumbled upon it on a SO answer.
Isn't it meant to establish only 1 database connection for the entire application?
If I do new Database()
in file A and new Database()
in file B, there still would be two connections.
I'm using a micro MVC framework if that's of any help.
class Database
{
private $pdo;
private $host;
private $databse;
private $username;
private $password;
public function __construct()
{
$this->host = Config::get('mysql/host');
$this->database = Config::get('mysql/database');
$this->username = Config::get('mysql/username');
$this->password = Config::get('mysql/password');
}
public function query($sql, $params)
{
$this->connect();
$sth = $this->pdo->prepare($sql);
$params = is_array($params) ? $params : [$params];
if ($sth->execute($params)) {
return $sth->fetch(PDO::FETCH_OBJ);
}
}
private function connect()
{
if (!$this->pdo) {
try {
$this->pdo = new PDO('mysql:host=' . $this->host . ';dbname=' . $this->database . ';charset=utf8', $this->username, $this->password);
} catch (Exception $e) {
die($e->getMessage());
}
}
}
}