I have a database class which extends PDO (and constructs it in its own constructor). For any model class I have that needs a database connection, I extend the database class for that model. So class DB extends PDO, and a model called UserInfoChange extends DB.
This allows me very easy access to writing sql queries without going through a pain the butt of connecting to the DB constantly or writing a bunch of boiler plate. I can just write $db_connection = $this->prepare($sql), bind my parameters, and execute. Very easy, very convenient. (I tried to model it after some other frame works.)
The problem: I have been profiling my code and it seems that database/PDO is being constructed for every class that extends the db that is instantiated, instead of just once. This is as expected due my architecture, but each DB/PDO class construction takes 10-20ms on my local machine, which is quite a bit (in context) and adds up for many models in play at once. I am trying to cut back on this, and just have one instantiation of PDO, instead of many. Would a static function be the answer here? Really have no idea how to go about cutting back here or what the best solution is.
Here is some example code (only a bare example, the real classes are much larger). (And forewarning: no validation takes place here, I handle validation in other classes that do usually do not access the database.)
DB class that extends PDO:
class DB extends PDO
{
public function __construct()
{
try
{
parent::__construct(DSN, USER, PASSWORD_DB);
$this->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$this->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
}
catch (PDOException $e)
{
// error handling
}
}
}
Now a Model-type class:
class UpdateUser extends DB
{
public $id_user;
public $username;
// Setters
public function setIDUser($id_user)
{
$this->id_user = $id_user;
}
public function setUserName($username)
{
$this->username = $username;
}
// Single Updates
public function updateUserName()
{
if (isset($this->username))
{
try
{
$sql = 'UPDATE users SET username = :username WHERE id_user = :id_user';
$dbq = $this->prepare($sql);
$dbq->bindValue(':username', $this->username);
$dbq->bindValue(':id_user', $this->id_user);
$dbq->execute();
}
catch (PDOException $e)
{
// error handling
}
}
}
}
Any ideas on the best way to preserve the convenience but also improve performance?