About the duplicate vote: This question is about the downsides of this approach, not about how to make this work; You can see it in this way: that question asks how to do something and the answer says something useful, however, I ask about the downsides of the answer.
TL;DR: will I encounter any technical difficulty by using this wrapper class later on? Why I haven't seen anything like this before?
I've been experimenting learning techniques for profiling recently and I found that creating the PDO instance is a place that could be optimized (~5ms). I don't need to use it in every call, however I'm creating it in every call from my code's structure. So, I just made this small class up:
<?php
namespace Library;
// Wrapper for \PDO. It only creates the rather expensive instance when needed.
// Use it exactly as you'd use the normal PDO object, except for the creation.
// In that case simply do "new \Library\PDO($args);" with the normal args
class PDO
{
// The actual instance of PDO
private $db;
public function __construct() {
$this->args = func_get_args();
}
public function __call($method, $args)
{
if (empty($this->db))
{
$Ref = new \ReflectionClass('\PDO');
$this->db = $Ref->newInstanceArgs($this->args);
}
return call_user_func_array(array($this->db, $method), $args);
}
}
To call it you only need to modify this line:
$DB = new \Library\PDO(/* normal arguments */);
And the type-hinting if you are using it to (\Library\PDO $DB)
.
It works flawlessly. It's also blazing fast (~0.2ms) when not using the PDO object and only introduces those ~0.2ms delay when using it (completely negligible). Now, I'm still learning about proper OOP, namespaces and general code structure, so I think I'm not qualified enough as to answer my own question yet:
Will I encounter any technical difficulty by using this wrapper class later on? Why I haven't seen anything like this before? therefore, why is this not more common or even default PDO behaviour?
Note: I intend to extend it furthermore by adding few more methods.