开发者

What are the disadvantages of using a PHP database class as a singleton?

What are开发者_开发知识库 the disadvantages of using a PHP database class as a singleton?


The disadvantages are the same as for any class that uses the Singleton pattern:

  • It is hard to test code that uses singletons.


If your DB class is built to only connect to a single database, you will have problems when you have a script that needs to connect to 2 two separate databases. However, you could build the singleton class to accept multiple server configurations, and then manage them within the singleton.

Otherwise, designing a database class as a singleton is a practice that makes a lot of sense, as you can maintain tight control over how many connections a script is making at any given time.


You can not use two database connections. You would want this because:

  • you have two databases.
  • you want to do something within a transaction when another transaction is already running on the 'current' database connection.
  • you want to use several mock database instances in your unit tests


It makes it hard to run unit tests against it and also makes it impossible to have multiple database connections. As we all know, global variables has lots of drawbacks and Singletons are no exception, only that they are a more "friendly" global variable.

I found a pretty good article about it and an old SO question as well.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜