Before everybody yells at me about why I wrote a PDO wrapper class, it's to avoid writing try
/catch
, prepare()
, execute()
, etc. each time a query should be executed.
I have pretty big website, so instead of repeating:
$sth = $dbh->prepare('Some query');
$dbh->BindParam('x', $x);
$dbh->BindParam('y', $y);
//..etc
$sth->execute();
a few thousands times I can simply do:
$res = $dbh->query('Some query', $x1, $y1, //etc);
$res->fetch(\PDO::FETCH_OBJ)
And also because I want to do some operations on each query like count queries, execution time, etc.
Is this Singleton wrapper really bad or overkill?
namespace App\Database {
class Database
{
static private $PDOObject;
function __construct()
{
if(!self::$PDOObject) {
try{
self::$PDOObject = new \PDO('mysql:host=127.0.0.1;dbname=test', 'username', 'pentagonpassword');
}
catch(\PDOException $e) {
//handle exception
throw $e;
}
return self::$PDOObject;
}
}
public function query($query, ...$params)
{
try
{
//start timer and other stuff (count queries etc)
$sth = self::$PDOObject->prepare($query);
$sth->execute($params);
//end timer
return $sth;
}
catch(\PDOException $e)
{
throw $e;
}
}
public function lastid($name = NULL)
{
return self::$PDOObject->LastInsertId($name);
}
//Other methods that processes some complex stuff
}
}