Steve Grunwell

Open-source contributor, speaker, and electronics tinkerer

A pile of LEGO bricks, ready to be constructed into something great (and blue).

Two new micro-libraries for WordPress

Last week, I found myself with two consecutive nights where my wife was busy with client work, so I found myself with some time after we put the toddler to bed. I had also had a stressful few weeks at work, where the things I was supposed to be working on kept getting de-prioritized so I could jump in and help other members of my team. Of course, ever-shifting priorities is nothing new for me (considering all but the last year and a half of my career has been in professional services), but it can still get frustrating when you just want to ship something.

https://twitter.com/EricMann/status/964383497321267200

A big part of what I do on a day-to-day basis is centered around WordPress. I work on the product team behind Liquid Web’s Managed WordPress and WooCommerce hosting platforms, and even when I’m writing Laravel applications they’re ultimately designed to support WordPress.

The more you work with WordPress, the more you see the same patterns repeating themselves. Registering scripts and styles, nonce verification, and custom meta boxes are things I can do in my sleep. Dig into third-party code and see yet another written using a Singleton pattern. Maybe the plugin author would appreciate if you refactored it to use namespaces, but of course there are no tests.

Sometimes you need a break, to just dig into something small enough that you can knock it out in a night or two but useful enough that you’re not coding for the sake of coding. That’s what I’ve done with two new micro-libraries: WP Cache Remember and One-Time Callbacks.

What’s a micro-library?

A pile of LEGO bricks, ready to be constructed into something great (and blue).

Photo credit: Iker Urteaga via Unsplash

The term “micro-library” may have been completely made up, to be honest. It’s not necessarily a plugin, but it’s also not a full-blown library that you’d feel bad about versioning as a dependency. Both of these packages are small files that are highly unlikely to change that can easily be embedded in another plugin, theme, or even WordPress core itself.

Both packages consist of single [necessary] files, containing a number of functions, wrapped in if ( ! function_exists( 'function_name' ) ) conditionals. If a dozen different plugins were to include these micro-libraries, the function would only be defined once, yet could all benefit from the functions provided by the micro-library.

Naturally, I’ve made both of these packages (and several others) available via Composer, as its the de facto PHP dependency manager; the WordPress community might be slow to adopt Composer, but developers who care about dependency management are already using it. They’re also both licensed under the super-permissive MIT license, so commercial themes and plugins are free to use them without worrying about licensing issues.

WP Cache Remember

The first of the two packages is the not-so-cleverly-named WP Cache Remember. Named for the first of the functions exposed by the micro-library, WP Cache Remember introduces six new functions that solve the same basic problem: returning early with a cached value.

Between the WordPress object cache, transients, and site transients, there are three different ways to cache WordPress data for a defined amount of time. Regardless of the caching method being used, their implementation often looks something like this:

  1. Determine the cache key.
  2. Check the cache for the given key.
    • If a value exists in the cache for the given key, return that value.
  3. Generate the value.
  4. Cache the value, so future calls within the cache window will be able to return at step 2.
  5. Return the now-cached value.

In practice, this often looks like:

With WP Cache Remember, that same code can be represented as:

The wp_cache_remember() function (along with remember_transient() and remember_site_transient(), for transients and site transients, respectively) borrows heavily from Laravel’s Cache::remember() method:

  1. Given a cache key and a function, check for a cached value.
    • If a cached value for that key exists, return it.
  2. If we don’t have a value, execute the function and cache its output before returning, using the provided cache key.

It’s a nice little wrapper that condenses a common pattern to a couple of lines. The other three functions (wp_cache_forget(), forget_transient(), and forget_site_transient()) act as convenience functions for deleting a cache value as soon as it’s retrieved, similar to:

The example above uses a closure (anonymous function) for the callback, but that function can be any PHP callable; if you’re still stuck in PHP 5.2 (a.k.a. the land before closures), you may also pass a named function:

As mentioned above, I’ve also submitted this recommendation to WordPress core, so maybe we’ll see wp_cache_remember() in a future release!

One-Time Callbacks

A year and one day before writing the package, I wrote this article on the Engineering @ Growella blog about one-time callbacks in WordPress. After receiving a lot of positive attention for WP Cache Remember, I decided to finally commit to it (literally) and release One-Time Callbacks:

While it’s uses are a bit more rare than WP Cache Remember might be, One-Time Callbacks are extremely useful when you need to perform an action or apply a filter exactly once, which is common when you’re extending third-party code.

What other micro-libraries are there?

Writing small, micro-libraries like these is a great way to spend an evening; the scope is small enough that they can be knocked out fairly easy, they’re largely free of heavy domain logic, and they’re also a great example of how to write WordPress tests that don’t have a lot of heavy coupling. I sincerely hope to see a community of small packages like this that others can pick up and use in their projects with confidence.

Previous

Writing WooCommerce Extensions with Confidence

Next

Customizing the WordPress TinyMCE Block Formats

1 Comment

  1. Is this something i can just add to a website i maintain to see performance improvements once installed, or does this require configuration by plugin developers for the plugins i use?

Leave a Reply

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

Be excellent to each other.