Last time, I argued in favor of the Singleton pattern in WordPress. Singletons make sense in WordPress specifically for several reasons:
- They live in the global scope without using the already abused/overused
- As a distributed application maintained by several hundred developers, they prevent problems that likely arise from others misusing your code
But one of the goals of object-oriented software development is to make your code reusable. The Singleton pattern as I explained it last time isn’t really applicable outside of WordPress. Typically, Singletons are a really bad idea. But rather than get hung up on the term and settle for the knee-jerk “it’s bad, don’t use it” conclusion, let’s take a deeper look. There’s a reason Singletons exist; they solve a specific problem. So rather than reject them out of hand, let’s make a minor change to make them safe for general PHP use.
There were two major arguments against Singletons throughout the comments, Twitter posts, Y Combinator thread, and private emails that followed my last post. First, that Singletons introduce hidden dependencies in your code. Second, that Singletons are nearly impossible to unit test. Both of these arguments are valid, but I have counters to each. [Read more…]