Make WordPress Core

Opened 7 years ago

#43341 new enhancement

Proposal: new cache helper functions

Reported by: stevegrunwell's profile stevegrunwell Owned by:
Milestone: Awaiting Review Priority: normal
Severity: normal Version:
Component: Cache API Keywords:
Focuses: Cc:

Description

I just tagged version 1.0.0 of WP Cache Remember, which is a small WordPress library that adds six new functions:

  • wp_cache_remember()
  • wp_cache_forget()
  • remember_transient()
  • forget_transient()
  • remember_site_transient()
  • forget_site_transient()

These functions all follow the same pattern, with two each for the WP object cache, transients, and site transients, respectively. The goal is to reduce this common pattern:

function get_some_value() {
  $cache_key = 'some-cache-key';
  $cached     = wp_cache_get( $cache_key );

  if ( $cached ) {
    return $cached;
  }

  $value = new WP_Query( /* ... */ );

  wp_cache_set( $cache_key, $value );

  return $value;
}

...to something easier to manage:

function get_some_value() {
  return wp_cache_remember( 'some-cache-key', function () {
    return new WP_Query( /* ... */ );
  } );
}

Of course, if the function is being used in WordPress core or anywhere else that needs to support PHP 5.2, any callable — not just closures — could be passed.

The function is based on Laravel's Cache::remember() method and is extremely useful for themes or plugins that are regularly making use of the object cache, transients, and/or site transients. The underlying code uses existing cache API functions, and thus won't require any modification in existing object cache adapters.

The complementary function, wp_cache_forget() will retrieve and empty the cache value, saving developers a step if they only want a cached value to be returned once (for instance, a "flash" message).

The GitHub README file has a full description of each function and its arguments, along with 100% test coverage. If there's any interest in including some or all of these helpers in core, I'd be more than happy to put together a PR.

Change History (0)

Note: See TracTickets for help on using tickets.