Of Libraries and The Singleton Pattern in WordPress

Over the past couple of years, I’ve written a number of articles about using design patterns in WordPress. One that I’ve written about a number of times has to do with the Singleton Pattern.

Although I’m not really expecting anyone to spend time reading through the following list, some of the articles and/or comments that discuss the pattern include:

The funny thing about blogging is that when you’ve written something two years, one year, or even six months ago, you may not feel the same way as you did when you initially wrote the post. And that’s fine – as far as I’m concerned, it’s an indication of professional growth (or just getting better at what you do).

So with that said, I don’t use the singleton pattern as much as I used to the reasons for which are a topic for another discussion. Instead, I was recently talking with a good friend about implementing the singleton pattern within the context of a WordPress plugin and the discussion really came down to this:

Should plugins that implement the singleton pattern be instantiated in a hook?

Make sense?

The Singleton Pattern in WordPress

For those of you who aren’t familiar with the Singleton Pattern, suffice it to say that it’s a design pattern that allows only a single instance of a class to be created.

If an instance doesn’t exist, it creates it and manages a reference to it internally, and returns it; otherwise, it simply returns the instance that was previously created.

It’s probably the simplest design pattern.

Though I’m not as much of a fan of this implementation as I once was, I still have a couple of projects on GitHub that show how to implement it. Eventually I’d love to update them but, you know, newer projects, other work, etc.

Anyway, all that to say that if you aren’t familiar with how the design pattern works, there are a few articles and examples mentioned earlier to get you up to speed.

A Formula for Object-Oriented WordPress Plugins

So, as I mentioned, a friend and I were talking about creating a plugin that implements the Singleton Pattern and how this should be used in comparison to other WordPress plugins.

Specifically, whenever anyone considers creating a WordPress plugin – especially using object-oriented techniques – they’re likely think of three things:

  1. Creating a class
  2. Creating a constructor
  3. Adding hooks into the constructor
  4. Setting the callbacks for the hooks as instance methods

This is the generic standard format (and stands to be improved) that’s seen most often.

From there, let’s that that you have a plugin that offers a collection of utility methods and it implements the Singleton Pattern. This raises the question: Should a class that implements the Single Pattern be instantiated within a hook such as plugins_loaded (or any other hook, for that matter)?

My short answer: No. I don’t think so.

Don’t Instantiate it There

You see, the whole idea behind the Singleton Pattern is that one-and-only-one instance of the class that implements that pattern will exist. To that end it doesn’t matter if you instantiate it with a hook in the context of the plugin, or if you attempt to get an instance to the plugin by simply calling the get_instance method at some point in your theme (or in another plugin).

All you’re really doing is determining a point at which the plugin is first instantiated, and the amount of work required to do so is usually so minimal – at least for classes that implement this pattern – that it’s you’re likely fine instantiating it the first time that you need it rather than using a hook in the plugin.

But this raises an interesting point: Assuming that you are going to implement the Singleton Pattern, perhaps it’s worth considering on the type of functions that the class is going to encapsulate.

If you’re looking to do some advanced object-oriented programming, then you’re likely not going to be using the Singleton Pattern as you’d be better off with static methods or even, even better, just a collection of functions.

This brings us to defining the class a library. In traditional programming sense (for lack of a better term), this means that it’s a collection, or a package of functions, that provide a clean interface for related operations.

And if we’re going to go that far, then perhaps it’s fair to say that all libraries are plugins, but not all plugins are libraries.

Then again, not all classes that implement the Singleton Pattern are libraries, right?

To clarify, the qualifying factor of if the class is a library is not whether or it implements a design pattern or not, but if it’s a class that encapsulates a group of related functions. Remember, in WordPress, we aren’t locked into using object-oriented programming anymore than we are locked into using procedural programming, so we could just as easily create a library of related with the same prefix.

This feels like it’d getting a bit muddled, doesn’t it?

Wait, What?

To pull it back and keep it simple, I’d summarize it like this:

  • If you’re creating a class that provides a clean interface to a set of related functions,
  • And if your class implements the Singleton Pattern,
  • Then you’ve created a library (which can be activated as a plugin)
  • But you do not need to get an instance of the class in the context of any hook.

Instead, you simply activate the plugin and then use it throughout your code as needed.

Obviously, this approach is more geared towards other developers are who are looking for some type of utility to use in their plugin or in their theme or WordPress-based application, but the point remains that the next time you’re looking at implementing the Singleton Pattern in WordPress, ask yourself if it’s presenting itself as a library.

If so, then it may be a fair implementation; otherwise, consider an alternative implementation.

6 Replies to “Of Libraries and The Singleton Pattern in WordPress”

  1. This article on dzone about only 2 roles in code is along similar lines conceptually I feel. I liked the way the author has separated code which acts on data and code which moves data around. I personally do not think it is quite that straightforward but the concept is interesting.

    And it strikes me that what you have written above suggest that plugin functionality can be split into similar roles.

    Functionality that is used by a plugin to integrate with WP and co-ordinate data. And functionality which goes in the library to manipulate/transform data in some way.

    1. Or perhaps to put it another way is like this:

      • Some plugins will introduce functionality that extends WordPress that allows users to enhance their experience.
      • Other plugins will introduce functionality that extends WordPress that allows developers to enhance their experience.

      I’d say that the former are simply defined as plugins, the latter may be better classified as libraries depending on their nature.

  2. Personally, I’m not a big fan of instantiating plugin classes on plugins_loaded (or any other action for that matter) either. However, my reasons differ from yours; they’re not limited to singleton classes either.

    I would consider instantiating the class at plugins_loaded bad practice because it nullifies the use of the action itself.

    plugins_loaded is intended to be the action called after all plugins have been loaded. Failing to instiate your plugin class before it’s called probably means not loading other plugin files, which other plugins might, in turn, want to use at plugins_loaded, for example to extend classes in another plugin.

    There’s no real reason to not instantiate it right away anyway, in just about all cases, because there shouldn’t be anything being carried out on loading the plugin anyway: all that should be done is adding callbacks to the proper hooks. After all, other plugins wouldn’t be able to extend the plugin by unhooking callbacks otherwise.

    My personally favourite approach is to instiate the main plugin class (singleton) directly, loading all plugin files but not carrying out any actual functionality, and then hooking into plugins_loaded to fire an action unique to the plugin (e.g. myplugin/loaded) passing the class instance. This allows you to maintain a beautiful hierarchy in plugins extending other plugins and makes sure you don’t have to rely on the further implementation of the plugin, providing an easy on-setup api call.

    1. I would consider instantiating the class at plugins_loaded bad practice because it nullifies the use of the action itself.

      In some cases, I agree – after tall, like you said, this is supposed to be after the plugins have been loaded; however, there are times in which resources are not yet available for certain plugins and we have to wait until later in the page lifecycle.

      On the contrary, it’s possible to instantiate plugins too early such that the resources they need aren’t available.

      I suppose there’s an argument here for how the plugin is architected, but in my experience – however limited that my really be – there’s no perfect hook for registering your plugin. It’s a matter of finding the most optimal place.

      My personally favourite approach is to instiate the main plugin class (singleton) directly, loading all plugin files but not carrying out any actual functionality, and then hooking into plugins_loaded to fire an action unique to the plugin (e.g. myplugin/loaded) passing the class instance.

      This isn’t a bad strategy. Personally, I’ve gotten away from using singleton patterns and use standard objects that have run methods or init methods (which then correspond to the init hook, for example).

      Again, I’m not making a case that singletons should be avoided completely (though I know some who are for that), I just think there are better times to use them rather than all the time. Otherwise, I think it raises the question of my not use static methods or just a collection of procedural functions, anyway.

      This allows you to maintain a beautiful hierarchy in plugins extending other plugins and makes sure you don’t have to rely on the further implementation of the plugin, providing an easy on-setup api call.

      This I agree with – it also banks on the fact that other developers will be able to understand how to leverage the API you’ve provided, how to properly unhook and rehook actions that they may modify, and so on.

      But for the more experienced WordPress – or event event-driven – developer, this offers a really clean way of setting things up.

  3. Hi, just come across the article from Google and want to learn more abt OOP development with WordPress plugin.

    Do you know any code examples that is implemented using the method you said above?

Leave a Reply

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