CacheEngine.php
3 years ago
CacheException.php
3 years ago
CacheNameSpaceTrait.php
3 years ago
ObjectCache.php
3 years ago
WPCacheEngine.php
2 years ago
CacheNameSpaceTrait.php
67 lines
| 1 | <?php |
| 2 | |
| 3 | namespace Automattic\WooCommerce\Caching; |
| 4 | |
| 5 | /** |
| 6 | * Implements namespacing algorithm to simulate grouping and namespacing for wp_cache, memcache and other caching engines that don't support grouping natively. |
| 7 | * |
| 8 | * See the algorithm details here: https://github.com/memcached/memcached/wiki/ProgrammingTricks#namespacing. |
| 9 | * |
| 10 | * To use the namespacing algorithm in the CacheEngine class: |
| 11 | * 1. Use a group string to identify all objects of a type. |
| 12 | * 2. Before setting cache, prefix the cache key by using the `get_cache_prefix`. |
| 13 | * 3. Use `invalidate_cache_group` function to invalidate all caches in entire group at once. |
| 14 | */ |
| 15 | trait CacheNameSpaceTrait { |
| 16 | |
| 17 | /** |
| 18 | * Get prefix for use with wp_cache_set. Allows all cache in a group to be invalidated at once. |
| 19 | * |
| 20 | * @param string $group Group of cache to get. |
| 21 | * @return string Prefix. |
| 22 | */ |
| 23 | public static function get_cache_prefix( $group ) { |
| 24 | // Get cache key - uses cache key wc_orders_cache_prefix to invalidate when needed. |
| 25 | $prefix = wp_cache_get( 'wc_' . $group . '_cache_prefix', $group ); |
| 26 | |
| 27 | if ( false === $prefix ) { |
| 28 | $prefix = microtime(); |
| 29 | wp_cache_set( 'wc_' . $group . '_cache_prefix', $prefix, $group ); |
| 30 | } |
| 31 | |
| 32 | return 'wc_cache_' . $prefix . '_'; |
| 33 | } |
| 34 | |
| 35 | /** |
| 36 | * Increment group cache prefix (invalidates cache). |
| 37 | * |
| 38 | * @param string $group Group of cache to clear. |
| 39 | */ |
| 40 | public static function incr_cache_prefix( $group ) { |
| 41 | wc_deprecated_function( 'WC_Cache_Helper::incr_cache_prefix', '3.9.0', 'WC_Cache_Helper::invalidate_cache_group' ); |
| 42 | self::invalidate_cache_group( $group ); |
| 43 | } |
| 44 | |
| 45 | /** |
| 46 | * Invalidate cache group. |
| 47 | * |
| 48 | * @param string $group Group of cache to clear. |
| 49 | * @since 3.9.0 |
| 50 | */ |
| 51 | public static function invalidate_cache_group( $group ) { |
| 52 | return wp_cache_set( 'wc_' . $group . '_cache_prefix', microtime(), $group ); |
| 53 | } |
| 54 | |
| 55 | /** |
| 56 | * Helper method to get prefixed key. |
| 57 | * |
| 58 | * @param string $key Key to prefix. |
| 59 | * @param string $group Group of cache to get. |
| 60 | * |
| 61 | * @return string Prefixed key. |
| 62 | */ |
| 63 | public static function get_prefixed_key( $key, $group ) { |
| 64 | return self::get_cache_prefix( $group ) . $key; |
| 65 | } |
| 66 | } |
| 67 |