全局可用的数据库连接,无需使用Global/Singleton
我正在创建一个新的 PHP 应用程序,并希望确保我做好了基础工作,以避免将来出现任何问题。我知道我的应用程序将有多个需要数据库连接(PDO)的类,并且在互联网上搜索了很长时间后我找不到明确的解决方案。
我个人喜欢单例设计模式,但是有很多人说一般情况下应该不惜一切代价避免单例。然而,这些人并没有给出这个问题的具体解决方案。
我知道一个应用程序可能需要多个数据库连接,但我不能创建一个包含每个所需数据库连接的单例(即 DB::getInst('conn1')->query(); )吗?
是否必须将 PDO(或 PDO 包装器)对象传递给可能需要它的每个类?我以前做过这个,发现跟踪它很烦人。
I'm creating a new PHP application and want to make sure I get the ground work right to save any future problems. I know my application will have more than one class that will need a database connection (PDO) and after a long time scouring the internet i can't find a definitive solution.
I like the singleton design pattern personally, but there are a lot of people out there that say singletons in general should be avoided at all costs. These people, however, don't give a specific solution to this problem.
I understand that an application may need more than one database connection but could i not create a singleton that contained each required DB connection (i.e. DB::getInst('conn1')->query(); )?
Is it a case of having to pass round the PDO (or PDO wrapper) object to every class that may need it? I've done this before found it annoying keeping track of it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我个人认为单例(或者多例,如果您需要多个数据库连接)适合这种用法。
但如果您不想使用它,则应该查看 Registry 模式。
这样,您就可以让数据库类实例可用于所有应用程序的类,而不必每次都传递额外的参数(恕我直言,这非常难看)。
I personally thing a singleton (or a multiton, if you need several DB connections) is fine for such an usage.
But if you do not want to use it, you should then take a look at the Registry pattern.
This way, you can have your database class instance(s) available for all your application's classes, without having to pass an additional parameter each time (which is very ugly, IMHO).
你可以,它被称为 multiton 模式
you can, it's called multiton pattern