Is there a use-case for singletons with database access in PHP?

Singletons have very little – if not to say no – use in PHP.

In languages where objects live in shared memory, Singletons can be used to keep memory usage low. Instead of creating two objects, you reference an existing instance from the globally shared application memory. In PHP there is no such application memory. A Singleton created in one Request lives for exactly that request. A Singleton created in another Request done at the same time is still a completely different instance. Thus, one of the two main purposes of a Singleton is not applicable here.

In addition, many of the objects that can conceptually exist only once in your application do not necessarily require a language mechanism to enforce this. If you need only one instance, then don’t instantiate another. It’s only when you may have no other instance, e.g. when kittens die when you create a second instance, that you might have a valid Use Case for a Singleton.

The other purpose would be to have a global access point to an instance within the same Request. While this might sound desirable, it really isnt, because it creates coupling to the global scope (like any globals and statics). This makes Unit-Testing harder and your application in general less maintainable. There is ways to mitigate this, but in general, if you need to have the same instance in many classes, use Dependency Injection.

See my slides for Singletons in PHP – Why they are bad and how you can eliminate them from your applications for additional information.

Even Erich Gamma, one of the Singleton pattern’s inventors, doubts this pattern nowadays:

“I’m in favor of dropping Singleton. Its use is almost always a design smell”

Further reading

  • How is testing the registry pattern or singleton hard in PHP?
  • What are the disadvantages of using a PHP database class as a singleton?
  • Database abstraction class design using PHP PDO
  • Would singleton be a good design pattern for a microblogging site?
  • Modifying a class to encapsulate instead of inherit
  • How to access an object from another class?
  • Why Singletons have no use in PHP
  • The Clean Code Talks – Singletons and Global State

If, after the above, you still need help deciding:

Singleton Decision Diagram

Leave a Comment