tags:

views:

125

answers:

4

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

+1  A: 

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.

Chris Henry
When 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
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
@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
+2  A: 

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

Gordon
A: 

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.

Martin Wickman
I think you mean "multiple database connections" per page, don't you?
greg0ire
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
@greg: Yup, at least with a classic `getInstance()` Singleton. Maybe the poster is searching for something like a database connection pool?
Martin Wickman
A: 

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
Sjoerd