Singletons in WordPress, Revisited (A Time and a Place?)

Before I start a post talking about using singletons in WordPress (or, more appropriately, the Singleton Pattern), I want to make sure that you read the following two articles:

Both of these articles provide immensely valuable perspective on this pattern and the dangers of using it whenever using it throughout our work in WordPress; however, does that mean we should completely avoid them?

I don’t think so.

Then again, I also recognize that the articles aren’t saying to completely avoid them. They are giving strong cases for how to use them and the dangers of using them should you opt to do so.

And though I’ve definitely used them in the past, I’ve generally stopped. However, I recently came across a use case for a project in which I think it’s acceptable.

Still Using Singletons in WordPress?

In order to give a reason as to why I even consider this particular pattern, I think it’s worth first understanding the use case. To put it simply:

  • There’s an administration page that allows the user to select how they would like to display the dates on the front-end of the site.
  • When the user saves the option, it will write the PHP-based format for the date to a table in WordPress.
  • When rendering a date, the value will be retrieved from the database and applied to the date that’s to be rendered.

And for those that are curious, there is only a handful – say four or five – ways that we’re allowing the user to display the date.

Because this particular project allows users to import CSVs of data (that include dates) and that allow them to render data from the CSVs albeit in a different format, it’s worth noting there’s a fair amount of date formatting happening on the back-end.

Naturally, a question arises:

Why not just format the date when the user imports their CSV?

And that’s because the user may opt to change the way the date is rendered after the CSV has been imported.

With that said, there’s this whole other mechanism in the plugin responsible for validating, sanitizing, and writing user input to the database.

But when it comes time to grabbing values from the database, especially when it comes in the form of reading a value from a database table, and doing so at multiple points throughout the application, wouldn’t it make sense to have a single point from which the value can be derived?

Singletons in WordPress: A high-level look at how this functions.
A high-level look at how this functions.

Or, another way of putting it, doesn’t it make sense to change one place in the application that can easily cascade throughout the rest of the application rather than searching for all of the possible places of:

  1. reading the option,
  2. making sure it’s set,
  3. defining a default if it’s not set,
  4. and returning the value?

And this is where I see a valid use of a singleton in WordPress coming into play: A way to read data at multiple points throughout the application. This carries with it, though, some implications:

  • the class doesn’t need to be instantiated more than once (I mean, that’s the whole idea of the singleton),
  • it won’t be dealing with mutable data,
  • it won’t be writing information or manipulating information.

In other words, it solely responsible for retrieving information and returning it. That’s it. Nothing else.

An Example Implementation

So what might this look like? Here’s a rough implementation for the purpose of conversation:

As you can see, it fulfills all of the points above. That is, it reads data, sets a default value, and then returns it.

This class does nothing other than reading and returning a very specific set of data.

A Caveat on Caching

Obviously, since this class is reading data from the database, it can be – and possibly should be – cached. The point of this post, though, is not to get into transients, expirations, and working through all of those nuances.

Instead, it’s about evaluating whether or not this is a valid use case for implementing a singleton in WordPress.

Wait, It Doesn’t Have to Be This Way!

I know, I know. Psych! I believe is the correct terminology, but let’s keep this professional-ish.

Up to this point, the whole post talked about why you may want to investigate using singletons in WordPress so that you have a way to easily retrieve information using consistently object-oriented principles.

But I still don’t think that using a singleton in WordPress is necessary here. At the very least, I think a static function is just fine. And the only reason I think that’s okay is because creating an instance of the class every time you need to access a function that retrieves data that won’t be changing within the class is overkill.

So what’s this look like?

And that, I believe, is a better solution that implementing an arbitrary design pattern when it’s not needed at all.

But I’m open to be convinced otherwise.

Thoughts From More Experienced Developers?

I’ve heard from a fellow friend and peer than simply using a namespaced function might even be the way to go. Clearly, there are a variety of ways to tackle this.

And with that, I’m interested to hear from the rest of you as to how you may refactor this even further. I’m not so much concerned with the implementation of the get function since it’s mainly put together for the demo.

Instead, I’m interested in ways to handle this outside of what’s presented here. Or, rather, just your take on what you see.

3 Replies to “Singletons in WordPress, Revisited (A Time and a Place?)”

  1. Is the idea to use the ::get() function from something like a view?

    Whatever class that is using Date_Formatter is going to be tightly coupled with Date_Formatter since the obvious way to call get will be via something like:

    echo date(Date_Formatter::get(), $timestamp);

    That coupling might never turn out to be a problem, or it might bite back when writing unit tests. Difficult to tell without knowing more about your project.

    Your Date_Formatter class is extremely simple and only have one external dependency, so one might argue that the introduced difficulty to write tests doesn’t introduce any risk.

    Still. I’d try the approach of using an non-static class/function and then spend my time trying to figure out the best way to hand over an instance to the cosumer, aka dependency injection.

  2. I found Singleton pattern useful for main plugin classes if they will hold settings data and some other stuff which can be requested more than once through a page load.

    WooCommerce and EDD are great examples where they hold cart data, sessions, settings etc.

    There are probably some other scenarios where singleton pattern can be used within WordPress but I have not found one yet.

    1. I found Singleton pattern useful for main plugin classes if they will hold settings data and some other stuff which can be requested more than once through a page load.

      I’m on the fence about it still and I lean in the direction of not using it, but I’m not totally convinced it shouldn’t be used for immutable cases.

      WooCommerce and EDD are great examples where they hold cart data, sessions, settings etc.

      Using a singleton to hold card data is an interesting thought. I’d have to study it to see. I tend to focus more on sessions and what not to handle that, but there’s also serialization around that should a user, say, abandon a cart of something.

      It’s a fun problem to solve :).

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.