Cache
Introduction
The cache wraps four backends behind one API, so calling code doesn't care where a value is stored. Added in wp-kit 2.4.0.
use YourPlugin\Deps\BitApps\WPKit\Cache\CacheManager;
$cache = (new CacheManager(['default' => 'transient', 'prefix' => 'yourplugin_']))->store();
$cache->put('user_123', $user, 3600);
$user = $cache->get('user_123');
Stores
$manager = new CacheManager([
'default' => 'transient',
'prefix' => 'yourplugin_',
'stores' => [
'file' => ['path' => WP_CONTENT_DIR . '/cache/yourplugin'],
'object' => ['group' => 'yourplugin_group'],
],
]);
$manager->store(); // the default store
$manager->store('file'); // a named one
| Store | Backing | Survives the request? |
|---|---|---|
array | PHP memory | No — gone on shutdown |
transient | WordPress transients | Yes |
object | WordPress object cache | Only with a persistent drop-in installed |
file | Filesystem, needs path | Yes |
transient is the default when no default is configured.
Operations
$cache->get('key', $default);
$cache->has('key');
$cache->put('key', $value, 3600); // ttl in seconds
$cache->add('key', $value, 3600); // only if absent
$cache->forever('key', $value);
$cache->forget('key');
$cache->flush();
$cache->pull('key'); // read and delete
$cache->increment('hits');
$cache->decrement('hits', 2);
remember() is the one worth reaching for — it returns the cached value, or runs the callback and stores the result:
$posts = $cache->remember('recent_posts', 3600, function () {
return get_posts(['numberposts' => 10]);
});
$config = $cache->rememberForever('config', fn () => build_config());
Facade
Cache forwards static calls to the default store, once a manager is set:
use YourPlugin\Deps\BitApps\WPKit\Cache\Cache;
Cache::setManager($manager); // once, during boot
Cache::put('key', $value, 600);
Cache::remember('recent_posts', 3600, fn () => get_posts());
Cache::store('file')->flush(); // a specific store
Using the facade before setManager() throws RuntimeException.
Store behavior worth knowing
TransientStore::flush()is a documented no-op — WordPress offers no way to enumerate transients by prefix. Clear individual keys withforget(), or use thefilestore when you need a real flush.- The
objectstore is per-request unless the site has a persistent object cache drop-in (Redis, Memcached). Without one it behaves likearray, which is easy to mistake for a caching bug.