Chris Kloberdanz
Chris Kloberdanz

Reputation: 4536

What the best way to access the database inside a class in PHP?

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?

Upvotes: 1

Views: 294

Answers (3)

Lucas Oman
Lucas Oman

Reputation: 15872

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.

Upvotes: 1

Noah Goodrich
Noah Goodrich

Reputation: 25263

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.

Upvotes: 1

Pēteris Caune
Pēteris Caune

Reputation: 45092

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

Upvotes: 3

Related Questions