| 1 |
<?php |
| 2 |
|
| 3 |
if ( ! defined( 'ABSPATH' ) ) { |
| 4 |
exit; |
| 5 |
} |
| 6 |
|
| 7 |
if ( ! class_exists( 'MywpCache' ) ) : |
| 8 |
|
| 9 |
final class MywpCache { |
| 10 |
|
| 11 |
private $cache_key = false; |
| 12 |
|
| 13 |
public function __construct( $cache_key = false ) { |
| 14 |
|
| 15 |
$cache_key = strip_tags( $cache_key ); |
| 16 |
|
| 17 |
if( empty( $cache_key ) ) { |
| 18 |
|
| 19 |
$called_text = sprintf( 'new %s( %s )' , __CLASS__ , '$cache_key' ); |
| 20 |
|
| 21 |
MywpHelper::error_require_message( '$cache_key' , $called_text ); |
| 22 |
|
| 23 |
return false; |
| 24 |
|
| 25 |
} |
| 26 |
|
| 27 |
$this->cache_key = $cache_key; |
| 28 |
|
| 29 |
} |
| 30 |
|
| 31 |
public function get_cache() { |
| 32 |
|
| 33 |
if( $this->cache_key === false ) { |
| 34 |
|
| 35 |
return false; |
| 36 |
|
| 37 |
} |
| 38 |
|
| 39 |
return wp_cache_get( $this->cache_key , 'mywp' ); |
| 40 |
|
| 41 |
} |
| 42 |
|
| 43 |
public function add_cache( $data = false ) { |
| 44 |
|
| 45 |
if( $this->cache_key === false ) { |
| 46 |
|
| 47 |
return false; |
| 48 |
|
| 49 |
} |
| 50 |
|
| 51 |
if( $data === false ) { |
| 52 |
|
| 53 |
return false; |
| 54 |
|
| 55 |
} |
| 56 |
|
| 57 |
$cache = $this->get_cache(); |
| 58 |
|
| 59 |
if( empty( $cache ) ) { |
| 60 |
|
| 61 |
$cache = array(); |
| 62 |
|
| 63 |
} |
| 64 |
|
| 65 |
$cache[] = $data; |
| 66 |
|
| 67 |
$this->update_cache( $cache ); |
| 68 |
|
| 69 |
return true; |
| 70 |
|
| 71 |
} |
| 72 |
|
| 73 |
public function update_cache( $data = false ) { |
| 74 |
|
| 75 |
if( $this->cache_key === false ) { |
| 76 |
|
| 77 |
return false; |
| 78 |
|
| 79 |
} |
| 80 |
|
| 81 |
if( $data === false ) { |
| 82 |
|
| 83 |
return false; |
| 84 |
|
| 85 |
} |
| 86 |
|
| 87 |
wp_cache_set( $this->cache_key , $data , 'mywp' ); |
| 88 |
|
| 89 |
$all_cache = wp_cache_get( 'all_cache' , 'mywp' ); |
| 90 |
|
| 91 |
if( empty( $all_cache ) ) { |
| 92 |
|
| 93 |
$all_cache = array(); |
| 94 |
|
| 95 |
} |
| 96 |
|
| 97 |
$all_cache[ $this->cache_key ] = $data; |
| 98 |
|
| 99 |
wp_cache_set( 'all_cache' , $all_cache , 'mywp' ); |
| 100 |
|
| 101 |
return true; |
| 102 |
|
| 103 |
} |
| 104 |
|
| 105 |
public function delete_cache() { |
| 106 |
|
| 107 |
if( $this->cache_key === false ) { |
| 108 |
|
| 109 |
return false; |
| 110 |
|
| 111 |
} |
| 112 |
|
| 113 |
return wp_cache_delete( $this->cache_key , 'mywp' ); |
| 114 |
|
| 115 |
} |
| 116 |
|
| 117 |
} |
| 118 |
|
| 119 |
endif; |
| 120 |
|