[wp-trac] [WordPress Trac] #43341: Proposal: new cache helper functions

WordPress Trac noreply at wordpress.org
Sat Feb 17 01:49:01 UTC 2018


#43341: Proposal: new cache helper functions
---------------------------+-----------------------------
 Reporter:  stevegrunwell  |      Owner:
     Type:  enhancement    |     Status:  new
 Priority:  normal         |  Milestone:  Awaiting Review
Component:  Cache API      |    Version:
 Severity:  normal         |   Keywords:
  Focuses:                 |
---------------------------+-----------------------------
 [https://github.com/stevegrunwell/wp-cache-remember 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:

 {{{#!php
 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:

 {{{#!php
 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 [https://laravel.com/docs/5.6/cache#cache-usage
 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).

 [https://github.com/stevegrunwell/wp-cache-remember#readme 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.

--
Ticket URL: <https://core.trac.wordpress.org/ticket/43341>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform


More information about the wp-trac mailing list