Skip to content

Instantly share code, notes, and snippets.

@markjaquith
Created February 6, 2013 22:59
Show Gist options
  • Save markjaquith/4726691 to your computer and use it in GitHub Desktop.
Save markjaquith/4726691 to your computer and use it in GitHub Desktop.
WordPress Object Cache wrapper I'm working on that has support for group purging.
<?php
if ( !class_exists( 'WP_Smart_Cache_v1' ) ) :
Class WP_Smart_Cache_v1 {
static $instances = array();
public function __construct() {
if ( function_exists( 'wp_cache_add_global_groups' ) )
wp_cache_add_global_groups( array( 'wp_smart_cache_global' ) );
}
public function instantiate( $group ) {
self::$instances[(string) $group] = new WP_Smart_Cache_Group_v1( (string) $group );
}
}
class WP_Smart_Cache_Group_v1 {
protected $version;
protected $group;
protected $global = false;
public function __construct( $group ) {
$this->set_group( $group );
}
protected function set_group( $group ) {
$this->group = (string) $group;
}
protected function wp_cache_group() {
if ( is_null( $this->version ) ) {
$wp_cache_group = 'wp_smart_cache' . $this->global ? '_global' : '';
$this->version = wp_cache_get( $this->group, $wp_cache_group );
if ( !$this->version )
$this->version = $this->purge();
}
return "{$this->group}__{$this->version}";
}
protected function generate_key( $length = 8 ) {
$chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
$key = '';
for ( $i = 0; $i < $length; $i++ ) {
$key .= substr($chars, wp_rand(0, strlen($chars) - 1), 1);
}
return $key;
}
public function set_global() {
if ( function_exists( 'wp_cache_add_global_groups' ) )
wp_cache_add_global_groups( array( $this->group ) );
$this->global = true;
return $this;
}
public function add( $key, $data, $expire = '' ) {
return wp_cache_add( $key, $data, $this->wp_cache_group(), $expire );
}
public function set( $key, $data, $expire = '' ) {
return wp_cache_set( $key, $data, $this->wp_cache_group(), $expire );
}
public function get( $key ) {
return wp_cache_get( $key, $this->wp_cache_group() );
}
public function delete( $key ) {
return wp_cache_delete( $key, $this->wp_cache_group() );
}
public function purge() {
$wp_cache_group = 'wp_smart_cache' . $this->global ? '_global' : '';
$this->version = $this->generate_key();
wp_cache_set( $this->group, $this->version, $wp_cache_group );
return $this->version;
}
}
function wp_smart_cache_instantiate() {
new WP_Smart_Cache_v1;
}
// Because we need to wait for wp_rand() to be available
add_action( 'plugins_loaded', 'wp_smart_cache_instantiate', 0 );
function wp_smart_cache( $group = NULL ) {
if ( !isset( WP_Smart_Cache_v1::$instances[(string) $group] ) )
WP_Smart_Cache_v1::instantiate( $group );
return WP_Smart_Cache_v1::$instances[(string) $group];
}
endif;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment