views:

130

answers:

3

I have a session class that needs to store session information in a MySQL database. Obviously I will need to query the database in the methods of this class. In general I may need to connect more than one database simultaneously and may or may not be connected to that database already.

Given that, what's the best way to access databases for the session class or any class for that matter. Would creating a class to manage connections make sense?

+3  A: 

I'd advise to check out this presentation, among other things it talks about best practices when accessing database:

http://laurat.blogs.com/talks/best_practices.pdf

Pēteris Caune
Nice link, thanks.
Philip Morton
+1  A: 

Database Connections are a prime example of when and where you can safely use a Singleton pattern; however, if you know that the Session Object will be a global object and it will be the only place that you need to create Database Connections, you could pretty safely store the db connections as instance members of the Session Class.

Noah Goodrich
Yeah, I use a singleton database class for all of my DB work.
Philip Morton
+1  A: 

Yes, I would use a DBAL. Either you can write your own, or you can use an existing solution like PDO. Even if using an existing solution, you may want to write a wrapper class that uses the singleton pattern so that a single connection can be shared with all parts of your code.

Lucas Oman
What about if I need to be connected to database A and database B at the same time? Would that be a singleton factory? Or would I need another wrapper around the singletons?
Chris Kloberdanz
I would write two more classes that extend the singleton, and only change the DB credentials. The singleton is important because it essentially creates a global, so you only need to connect once to each DB.
Lucas Oman