I know the title doesn’t give much clues about what I’m asking for, so here’s the simplified situation:
class MyPDO extends PDO
{
private $stmt;
function __construct($dsn...)
{
parent:__construct($dsn...);
}
function myQuery($sql)
{
$this->stmt = $this->query($query);
}
function myFetchAll()
{
return $this->stmt->fetchAll($mode);
}
function myFetchRow()
{
return $this->stmt->fetch();
}
}
Throughout the application I have a base instance of MyPDO and pass it to different objects, mappers.
$adapter = new MyPDO($dsn...);
$adapter->myQuery('SELECT * FROM table');
$rows = $adapter->myFetchAll();
$another_object = new ObjectThatNeedsPDO($adapter);
$another_object->adapter->myQuery('SELECT * from another_table');
$rows = $another_object->adapter->myFetchAll();
Is this approach safe, especially from the MyPDO::stmt perspective? Can the application flow mess things up so I can end up fetching data from another $stmt than expected?
Personally, I would not take your approach. The reason being that I would not want the possibility of a statement object created by one class being exposed to another unrelated class. Additionally, each implementing class may have different sorts of parameter binding which it needs to perform, ways in which it needs to access the data (i.e. fetch all rows, fetch each row, fetch as objects vs. arrays, etc.), ways in which to handle errors in a class-specific way, and so forth.
To me you are gaining nothing by having this logic inside of some child of the base PDO class. I mean is it really much harder to do:
than:
What do you gain other than a unnecessary coupling of this additional class to all the classes which will consume it? Really, the statement interactions are always going to be very class specific with really the only common functionality (the DB connection) being provided by the base PDO instance.
As such, certainly feel free to pass around a common PDO instance amongst classes, this is definitely a good practice (i.e. dependency injection).
Just think really hard about whether you want to potentially change every single implementing class when you make changes to your proposed myPDO class, or whether you want to change your myPDO class every time some implementing class needs some custom means to interact with the statement object.
Based on discussions below, it seems you may want to consider extending PDOStatement to give you the maximum flexibility.
This might look like this:
Usage example: