duckdev / wp-cache-helper
WordPress对象缓存和transients的辅助类,具有分组刷新功能。
v1.0.0
2021-08-08 19:49 UTC
Requires
- php: >=5.6
README
WP Cache Helper
WP Cache Helper是一个简单的WordPress库类,用于引入方便的新缓存功能。
构建以支持WordPress对象缓存的分组缓存刷新功能,该功能核心尚未支持。
- 灵感来源于WP Cache Remember。
此辅助工具可以简化以下内容
function do_something() { $cache_key = 'some-cache-key'; $cached = wp_cache_get( $cache_key ); // Return the cached value. if ( $cached ) { return $cached; } // Do all the work to calculate the value. $value = a_whole_lotta_processing(); // Cache the value. wp_cache_set( $cache_key, $value ); return $value; }
这种模式运行良好,但代码重复很多。此包从Laravel的Cache::remember()
方法中汲取灵感;使用Cache::remember()
,上面的相同代码变为
// Use this as a global variable or something. $cache = new \DuckDev\Cache\Cache(); function do_something() { return $cache->remember( 'some-cache-key', function () { return a_whole_lotta_processing(); } ); }
安装
在项目中安装此库的推荐方法是通过Composer
$ composer require duckdev/wp-cache-helper
使用方法
WP Cache Remember为WordPress提供了以下功能
$cache->remember()
$cache->forget()
$cache->persist()
$cache->cease()
$cache->flush_group()
$cache->flush()
每个函数都会检查回调的响应是否为WP_Error
对象,以确保您不会长时间缓存临时错误。PHP异常也不会被缓存。
$cache->remember()
从对象缓存中检索值。如果不存在,则运行$callback
来生成和缓存该值。
参数
- (string) $key
- 缓存键。
- (callable) $callback
- 用于生成和缓存值的回调。
- (string) $group
- 可选。缓存组。默认为空。
- (int) $expire
- 可选。缓存条目应在多少秒后过期。默认为0(尽可能长)。
示例
function get_latest_posts() { return $cache->remember( 'latest_posts', function () { return new WP_Query( array( 'posts_per_page' => 5, 'orderby' => 'post_date', 'order' => 'desc', ) ); }, 'my-cache-group', HOUR_IN_SECONDS ); }
$cache->forget()
从对象缓存中检索并随后删除一个值。
参数
- (string) $key
- 缓存键。
- (string) $group
- 可选。缓存组。默认为空。
- (mixed) $default
- 可选。如果给定键不存在于对象缓存中,则返回的默认值。默认为null。
示例
function show_error_message() { $error_message = $cache->forget( 'form_errors', 'my-cache-group', false ); if ( $error_message ) { echo 'An error occurred: ' . $error_message; } }
$cache->persist()
从transients中检索值。如果不存在,则运行$callback
来生成和缓存该值。
参数
- (string) $key
- 缓存键。
- (callable) $callback
- 用于生成和缓存值的回调。
- (string) $site
- 应使用站点transients。
- (int) $expire
- 可选。缓存条目应在多少秒后过期。默认为0(尽可能长)。
示例
function get_tweets() { $user_id = get_current_user_id(); $key = 'latest_tweets_' . $user_id; return $cache->persist( $key, function () use ( $user_id ) { return get_latest_tweets_for_user( $user_id ); }, 15 * MINUTE_IN_SECONDS ); }
$cache->cease()
从transient缓存中检索并随后删除一个值。
参数
- (string) $key
- 缓存键。
- (string) $site
- 应使用站点transients。
- (mixed) $default
- 可选。如果给定键不存在于transients中,则返回的默认值。默认为null。
$cache->flush_group()
刷新缓存组项。使用此方法,而不是刷新整个缓存。
参数
- (string) $group
- 缓存组名称。
$cache->flush()
包装wp_cache_flush
,以检查是否可用其他方法进行刷新,如果wp_cache_flush
被禁用。
鸣谢
- 由Joel James维护