Skip to content

Instantly share code, notes, and snippets.

@pippinsplugins
Forked from markjaquith/gist:2653957
Last active December 18, 2015 13:19
Show Gist options
  • Save pippinsplugins/5788774 to your computer and use it in GitHub Desktop.
Save pippinsplugins/5788774 to your computer and use it in GitHub Desktop.
Modified version of Mark's class that includes a flush() member function.
<?php
/*
Usage:
$frag = new CWS_Fragment_Cache( 'unique-key', 3600 ); // Second param is TTL
if ( !$frag->output() ) { // NOTE, testing for a return of false
functions_that_do_stuff_live();
these_should_echo();
// IMPORTANT
$frag->store();
// YOU CANNOT FORGET THIS. If you do, the site will break.
}
*/
class CWS_Fragment_Cache {
const GROUP = 'cws-fragments';
var $key;
var $ttl;
public function __construct( $key, $ttl ) {
$this->key = $key;
$this->ttl = $ttl;
}
public function output() {
$output = wp_cache_get( $this->key, self::GROUP );
if ( !empty( $output ) ) {
// It was in the cache
echo $output;
return true;
} else {
ob_start();
return false;
}
}
public function flush() {
wp_cache_delete( $this->key, self::GROUP );
}
public function store() {
$output = ob_get_flush(); // Flushes the buffers
wp_cache_add( $this->key, $output, self::GROUP, $this->ttl );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment