So this is something I\'ve been meaning to get to grips with for ages. Converting a few small (single-file) applications to PDO. I can use PDO, connect to a database and run
You do not need to extend from PDO here. What you want is a central place in your application that is creating the PDO object. You can then do the changes you like over time (e.g. integrating some configuration file/system) and extend then centrally.
One thing is that you create a class for that, let's call it PdoFactory
:
class PdoFactory
{
/**
* @return PDO
*/
public function buildPdo() {
$pdo = new PDO($dsn = 'xyz', $user = 'abc', $pass = '', $options = '');
if ($pdoException = true) {
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
return $pdo;
}
}
Usage:
$factory = new PdoFactory();
$pdo = $factory->buildPdo();
As you can see, this is very easy to use. You can even put the place where you create the PdoFactory
apart from the place where you invoke the buildPdo()
function.
Also this makes it more clear that you are dealing with two different things here: First creating the Pdo object (encapsulated into a class of it's own) and the Pdo object itself which is just for accessing the database.
I hope this helps.
The problem, as I see it, is that you are hard-coding a particular error level into your application. What if you're in development and you want everything? What if you decide you want to change the level for a particular application? It would be much better to keep it as a parameter you set after the fact, or, if you're bent on subclassing it, pass an error level in as a constructor argument.