Skip to content

Instantly share code, notes, and snippets.

@danlamanna
Created October 29, 2011 22:34
Show Gist options
  • Save danlamanna/1325185 to your computer and use it in GitHub Desktop.
Save danlamanna/1325185 to your computer and use it in GitHub Desktop.
Pods Caching Examples
<?php
define('CACHE_DURATION', 1800); // 30 mins
define('PODS_CACHE_GROUP', 'pods_plugin');
// Example of pods->find() method with database caching
public function find ($params, $limit = 15, $where = null, $sql = null) {
// Cache key is combo of current pod id, and query string of arguments
// May want to prefix with pods_plugin?
$findPodCacheKey = $this->id . http_build_query(array($params, $limit, $where, $sql));
// Return a cached value from DB right away if exists
if ($cachedFind = get_transient($findPodCacheKey)) {
return $cachedFind;
}
// Do normal find methods
set_transient($findPodCacheKey, $findResults, CACHE_DURATION);
return $findResults;
}
// Example of pods->find method with object caching
public function find ($params, $limit = 15, $where = null, $sql = null) {
$findPodCacheKey = $this->id . http_build_query(array($params, $limit, $where, $sql));
// Return a cached value from object cache if it exists
if ($cachedFind = wp_cache_get($findPodCacheKey, PODS_CACHE_GROUP)) {
return $cachedFind;
}
// Do normal find methods
// Noteworthy: wp_cache_set is essentially an upsert, wp_cache_add does exist
// with the same arguments
wp_cache_set($findPodCacheKey, $findResults, PODS_CACHE_GROUP, CACHE_DURATION);
return $findResults;
}
public function clearAllPodsCache() {
// Flush all object caching
// Unfortunately you can't delete cache on a per group basis, so ALL object caching would have to be cleared
wp_cache_flush();
// Alternatively, if we wanted to store existing cache keys we could delete each one individually via:
// wp_cache_delete(id, PODS_CACHE_GROUP)
// Transient caching can only be deleted on a per key-name basis
// So perhaps we should store all transients starting with the pods cache group,
// so we can do a like query to remove all of ours.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment