Skip to content

Commit 576aa25

Browse files
committed
Initial commit
1 parent beb7ff2 commit 576aa25

1 file changed

Lines changed: 66 additions & 0 deletions

File tree

app/Cache.php

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
<?php
2+
namespace Nimbium\MyPlugin;
3+
4+
class Cache extends Plugin {
5+
6+
/**
7+
* Retrieves value from cache, if enabled/present, else returns value
8+
* generated by callback().
9+
*
10+
* @param string $key Key value of cache to retrieve
11+
* @param function $callback Result to return/set if does not exist in cache
12+
* @return string Cached value of key
13+
*/
14+
public static function get_object( $key = null, $callback ) {
15+
16+
$object_cache_group = self::$settings['object_cache_group'] ?: sanitize_title( self::$settings['data']['Name'] );
17+
$object_cache_expire = self::$settings['object_cache_expire'] ?: 86400; // Default to 24 hours of null
18+
19+
// Set key variable
20+
$caller = end( debug_backtrace( DEBUG_BACKTRACE_IGNORE_ARGS, 2 ) );
21+
$caller_class_name = strtolower( end( explode( "\\", $caller['class'] ) ) );
22+
$object_cache_key = $caller_class_name . '_' . $caller['function'] . ( $key ? '_' . $key : '' );
23+
24+
// Try to get the value of the cache
25+
$result = wp_cache_get( $object_cache_key, $object_cache_group );
26+
27+
// If result wasn't found/returned and/or caching is disabled, set & return the value from $callback
28+
if(!$result) {
29+
$result = $callback();
30+
wp_cache_set( $object_cache_key, $result, $object_cache_group, $object_cache_expire);
31+
}
32+
33+
return $result;
34+
35+
}
36+
37+
/**
38+
* Flushes the object cache, if enabled. Parameters are not used but are
39+
* when passed by 'publish_post' action hook.
40+
*
41+
* Example usage: Cache::flush();
42+
*
43+
* @param int $ID The ID of the post being published
44+
* @param WP_Post The post object that is being published
45+
* @return mixed Returns success as JSON string if called by AJAX,
46+
* else true/false
47+
*/
48+
public static function flush($ID = null, $post = null) {
49+
50+
$result = ['success' => true];
51+
52+
try {
53+
wp_cache_flush();
54+
} catch (Exception $e) {
55+
$result = ['success' => false, 'message' => $e->getMessage()];
56+
}
57+
58+
if( defined('DOING_AJAX') && DOING_AJAX ) {
59+
echo json_encode($result);
60+
wp_die();
61+
}
62+
return $result['success'];
63+
64+
}
65+
66+
}

0 commit comments

Comments
 (0)