PDO with a pool of reusable connections

3.2k Views Asked by At

I've created a class (called DBPDO) that extends the standard PDO class (class DBPDO extends PDO {}) in order to have all the methods and properties that come with PDO with the addition of more control on the queries (ie. profiling when developing, etc...) and methods that permit to speed up the work when coding queries.

I'd like to improve this class. I'm thinking about all the connections that are created throughout the website, most of all are created inside different scopes to perform independent queries. So I'm wondering: why do I have to create ie. 5 connections on 5 different methods/classes/functions of my application, when I could use the same connection on all of them?

I don't want to use persistent connections (for example read What are the disadvantages of using persistent connection in PDO).

I'd just like to have a class that - when instantiated - gives me an already active connection, if exists, or gives me a new one.
There is a problem, though. What if I have to visit the results of a query and perform another query at each result? I necessarily need two different connections. So I'll need to tell this new class if I want a brand new connection or a used one.

I was thinking of writing a new class PDOConn, with an static method getConnection($forceNew = false) {} and an static private property $Connections = array().

When I need a connection, I write:

$dbh = PDOConn::getConnection();

PDOConn will look if $Connections already contains at least one connection (in form of an instance of my already working DBPDO class) and reaturns that object. If $Connections is empty, it will create a new object (instance of DBPDO), adds that object to $Connections and returns it.

If I want to force the creation of a new connection, I'll write:

$dbh = PDOConn::getConnection(true);

So it will create a new connection and adds it to $Connections. When getConnection is called again without forcing a new creation, PDOConn will return the first created connection (or maybe the last one?).

Questions
Do you think this is a good way, a good idea? Do you have any better suggestion? Most of all: do you think that there's something I didn't consider in my PDOConn class functionality that could cause me problems I'm not figuring out right now? Do you think that writing a class like that is worthy to manage PDO connections? I mean, I started this thread because I wanted to reuse connections when it's not necessary to create new ones: is this worthy/relevant or I can continue creating how many connections I want, it doesn't matter?

Thank you.

0

There are 0 best solutions below