什么最好的方法访问数据库在一个PHP类?What the best way to access the database inside a class in PHP?

- 此内容更新于:2014-12-30
主题:

原文:

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?

解决方案:
我建议看看这个演示,除此之外它谈论最佳实践当访问数据库: http://laurat.blogs.com/talks/best_practices.pdf
原文:

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

Philip Morton的回复:很好的链接,谢谢。

(原文:Nice link, thanks.)

tereško的回复:链接是坏了。

(原文:link is broken.)

解决方案:
数据库连接时的典型例子,您可以安全地使用单例模式;然而,如果您知道会话对象将是一个全局对象,它将是唯一的地方,您需要创建数据库连接,你可以很安全地存储数据库连接会话类的实例成员。
原文:

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.

Philip Morton的回复:是的,我使用一个单例为我所有的DB数据库类的工作。

(原文:Yeah, I use a singleton database class for all of my DB work.)

解决方案:
是的,我将使用一个DBAL。您可以编写您自己的,或者您可以使用一个现有的解决方案如PDO。即使使用一个现有的解决方案,您可能想要编写一个包装器类,使用单例模式,这样一个连接可以共享代码的所有部分。
原文:

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.

Chris Kloberdanz的回复:什么如果我需要被连接到数据库和数据库在同一时间?这是一个单例工厂吗?或者我需要另一个单件包装?

(原文: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?)

Lucas Oman的回复:我会写两个单例类的,,只有改变DB的凭证。独立是很重要的,因为它创造了一个全球性的,所以你只需要每个数据库连接一次。

(原文: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.)