Singleton or Dependency Injection pattern for database connection

Normally, a good googling session would suffice to answer most of my questions, but $this isn't one of them. Thus, it's is my first question here :

A lot of people (at SO and elsewhere) say that Singletton is bad. Actually so bad that some fellow developers even consider it as an Anti-Christ Anti-Pattern and should be replaced by Dependency Injection Pattern. The only exception to this 'rule' is with loggers (well, almost).

Some argue that because in PHP variables are at most 1 request-old ...

[...] one of the two main purposes of a Singleton is not applicable here.

But during that one request, multiple fetches from the Database may/will occur. Database is a shared resource between ALL the requests and if I don't make sure that there's as few connections as possible, I may get struck with a max_connections error (just an example).

So, if Singleton is a bad design in most cases, what about managing Database connections ? Is Singleton a good idea or I should opt for DI ?

Thanks in advance : )

Upvotes: 0

Views: 2348

Answers (2)

kormik
kormik

Reputation: 869

The Singleton pattern for database connection is also bad idea. How many connection to database you use (or need) depends on your application design.

You can use same instance of database connection class in whole request, but without using singleton pattern.

Upvotes: 0

duffymo
duffymo

Reputation: 308743

A Singleton is a bad design in this case. Google would say it's a bad idea in all cases.

The right answer here is the connection pool.

You can avoid a max connections issue by configuring your pool to remain well below the limit and by making sure that your code rigorously closes all connections as soon as you're done with them. The cycle should be very short: check out of pool, execute SQL, close connection.

Upvotes: 2

Related Questions