Skip to content

Instantly share code, notes, and snippets.

@zacscott
Last active March 11, 2017 11:08
Show Gist options
  • Save zacscott/9191d5a384e7e92afff3 to your computer and use it in GitHub Desktop.
Save zacscott/9191d5a384e7e92afff3 to your computer and use it in GitHub Desktop.
Fragment caching utility class for WordPress. Based off; https://gist.github.com/markjaquith/2653957
<?php
/*
* Plugin Name: Fragment Cache
* Description: Fragment cache provider plugin
* Version: 1.2
* Author: Zachary Scott
*/
namespace zacscott;
/**
* Simple fragment cache utility which uses WP transients. Site transients are
* used to support multi site installations.
*
* Use like so:
*
* $cache = new FragmentCache( 'my-fragment', 3600 ); // cache for an hour
* if ( ! $cache->output() ) :
*
* echo some_heavy_lifting_here();
*
* $cache->store(); // NOTE this is important otherwise it will break your site
* endif;
*
* Based off the fragment cache by Mark Jaquith;
* https://gist.github.com/markjaquith/2653957
*
* @author Zachary Scott <[email protected]>
*/
class FragmentCache {
private $key;
private $ttl;
/**
*
* @param $key Unique key for this fragment cache.
* @param $ttl Time the fragment is cached for in seconds. If set to 0, it
* will ever expire.
*/
public function __construct( $key, $ttl ) {
assert( ! empty( $key ) );
assert( is_numeric( $ttl ) );
$this->key = (string) $key;
$this->ttl = (int) $ttl;
}
/**
* Output the fragment from the cache if present.
*
* @return boolean Whether the fragment was in the cache.
*/
public function output() {
$output = get_site_transient( $this->get_key() );
if ( ! empty( $output ) ) { // It was in the cache
echo "<!-- frag {$this->key} - cached -->\n";
echo $output;
echo "<!-- /frag {$this->key} -->\n";
return true;
} else {
echo "<!-- frag {$this->key} - building -->\n";
ob_start();
return false;
}
}
/** Stored the recorded fragment output and stores it in the cache. */
public function store() {
$output = ob_get_flush();
set_site_transient( $this->get_key(), $output, $this->ttl );
echo "<!-- /frag {$this->key} -->\n";
}
/** Deletes the fragment from the cache */
public function delete() {
delete_site_transient( $this->get_key() );
}
// Returns the transient key for the cache
private function get_key() {
return 'frag-' . md5( $this->key ); // NOTE must be < 40 chars
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment