I was thinking through some DAO design stuff with a teammate and came across an interesting question about which I have yet to find any best practices guidelines.
When creating a DAO object, when should the DB connection occur? We’ve talked through instantiating an object that creates a DB connection in a constructor (then uses it in subsequent methods) and making a static class that establishes a connection and tears it down after every method call.
Both have clear performance implications based on environment – a static object would be good for a few intermittent calls whereas instantiating an object that holds a connection would be great for a number of calls in a short amount of time for a small number of users.
Is there another way to do this? Perhaps something that would be better for performance across most situations?
The best way to deal with this issue would be to have factory, which create the data access objects within your model layer. This would have several advantages:
This is how I would implement something like it:
And the usage would look something like this:
Then you pass the
$daoFactoryvariable to whichever object will require to create DAO. This way, if need arises, you can easily replace the factory (as long as it implements samecreate()method footprint), with something completely different. And your domain business logic is in no way impacted by such a change.The objects which use this factory became completely unaware that there even exists a database connection, and that DAOs need it to function. And you can even end up with situations, when you don’t even need to establish a connection to database.