PHP 单例数据库限制
好吧,这种情况经常出现,我想我应该请 Stack Overflow 上的一些聪明人来帮助我。
我读过,当您想要创建数据库连接以返回一个实例时,应该使用单例模式。这一切都很好,但这是否会限制您只能使用一个连接?由于单例仅返回对象的单个实例。
假设我有一个方法返回类构造函数的单个实例,该构造函数根据用户指定的参数创建连接,或者说在配置文件中,然后用户想要创建到另一个数据库的第二个连接,单例不会只返回原始连接,因此它限制用户创建多个数据库连接吗?
Okay, so this is cropping up alot, and I figured i'd ask some of the wise people over at Stack Overflow to help me out here.
I have read up that you should use the Singleton Pattern when you want to create a database connections in order to return one instance. This is all well and good, but doesn't this restrict you to only one connection? Since the singlton only returns a single instance of an object.
So say I had a method that return the single instance of a class contrustor that constructor created a connection based on the paramteres specified by the user, or say in a configuration file, and then user would want to create a second connections to another database, wouldn't the singleton just return the original connection, therefore it restricts the user from creating multiple database connections?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我可以通过多种方式看到实现,包括:
1)单例保存成员数据,包括与数据库 A 的连接和另一个包含与数据库 B 的连接的成员变量
。2)与 #1 相同,但假设您需要一个连接池到每个数据库,这样你就可以保留 2 个包含连接的数组。当然,这些都可以同时连接,但更好的是,您可以延迟连接它们,但维护这个数组(达到某个最大连接数)。
I can see the implementation in various ways including:
1) The singleton holds onto member data including a connection to database A and another member variable containing a connection to database B.
2) Same as #1 but let's say you want a pool of connections to each database so then you would hold onto 2 arrays containing the connections. Of course these can all be connected at once, but better yet you would lazy-connect them but maintaining this array (to some max number of connections).
您可以使用
Singleton
模式来创建Connections
类。该类管理多少个连接取决于您,例如您可以保留一个连接,或者可以使用对象池类型模式来管理连接池。You could use the
Singleton
pattern to create aConnections
class. It is up to you how many connections this class manages for example you could keep one connection or you could use an object pool type pattern to manage a pool of connections.