What are the disadvantages of using a PHP database class as a singleton?
4 Answers
The disadvantages are the same as for any class that uses the Singleton pattern:

- 312,688
- 75
- 539
- 559
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.

- 11,914
- 3
- 30
- 31
-
1When you have to deal with multiple databases, then use the "Registry" design pattern (which looks like a singleton associative array), and Use the connection DSN as a registry key. – greg0ire Jun 26 '10 at 15:50
-
The Registry pattern is a horrible solution. Just use a multiton and provide key/value pairs (where the key is the name of the connection, eg "connection_1" and the value is the connect info (username/pass, host, database name, etc)) and have all of your connection objects stored within the multiton. Registry objects really have no place anywhere as they're little more than glorified global variables. – Adrian Jun 26 '10 at 16:42
-
@Adrian, I totally agree. The whole point of using a singleton / multiton pattern is avoid, at all costs, creating a second db connection within the same script. The Registry pattern just doesn't seem to solve any of the issues present here. – Chris Henry Jun 27 '10 at 03:59
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.

- 1
- 1

- 19,662
- 12
- 82
- 106
-
I think you mean "multiple database connections" per page, don't you? – greg0ire Jun 26 '10 at 15:51
-
Yes that's true. If not using singleton, I end up to have, with the application I am developing, at least 4 database connections in every point of time. I was just wondering whats less problematic... – Ricardo Jun 26 '10 at 16:02
-
@greg: Yup, at least with a classic `getInstance()` Singleton. Maybe the poster is searching for something like a database connection pool? – Martin Wickman Jun 26 '10 at 16:23
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

- 74,049
- 16
- 131
- 175