Skip to content

ObjectCache

Daniel M. Hendricks edited this page Aug 26, 2017 · 3 revisions

The ObjectCache class is intended to make it easy to reduce database calls and other resource-intensive operations.

  • If object caching is enabled and the key exists, it will be return from cache.
  • If either of the above are not true, it will fetch and return the current value.

Instantiation

use WordPress_ToolKit\ObjectCache;

$cache = new ObjectCache( 'object_cache' => [
  'group' => 'my_plugin_cache',
  'expire_hours' => 72 ]
);

Simple Example

$my_option = $cache->get_object( 'cache_key_name', function() {
  return get_option( '_my_option_name' );
});

Carbon Fields Example

$my_option = $cache->get_object( 'carbon_field_name', function() {
  return carbon_get_theme_option( 'carbon_field_name' );
});

Flushing the Cache

$cache->flush();

Testing

An easy way to test object caching locally is to install Local by FlyWheel (which loads sites in virtual machines and also includes Redis) and:

  1. Create a new site.
  2. Install and activate the Redis Object Cache plugin.
  3. Click the Enable Object Cache button in Settings > Redis.

You can now enable/disable/flush the cache and test to make sure that everything is functioning as expected. Example:

var_dump( time() );

$time = $cache->get_object( 'php_time', function() {
  return time();
});

var_dump( $time );
Clone this wiki locally