在PHP中访问类中数据库的最佳方法是什么?

时间:2022-01-14 02:48:50

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.

我有一个会话类,需要在MySQL数据库中存储会话信息。显然我需要在这个类的方法中查询数据库。通常,我可能需要同时连接多个数据库,可能已经或可能没有连接到该数据库。

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 个解决方案

#1


3  

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

#2


1  

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.

数据库连接是您可以安全使用Singleton模式的时间和地点的主要示例;但是,如果您知道会话对象将是一个全局对象,并且它将是您创建数据库连接所需的唯一位置,则可以非常安全地将数据库连接存储为会话类的实例成员。

#3


1  

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.

是的,我会使用DBAL。您可以自己编写,也可以使用PDO等现有解决方案。即使使用现有解决方案,您也可能希望编写一个使用单例模式的包装类,以便可以与代码的所有部分共享单个连接。

#1


3  

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

#2


1  

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.

数据库连接是您可以安全使用Singleton模式的时间和地点的主要示例;但是,如果您知道会话对象将是一个全局对象,并且它将是您创建数据库连接所需的唯一位置,则可以非常安全地将数据库连接存储为会话类的实例成员。

#3


1  

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.

是的,我会使用DBAL。您可以自己编写,也可以使用PDO等现有解决方案。即使使用现有解决方案,您也可能希望编写一个使用单例模式的包装类,以便可以与代码的所有部分共享单个连接。