Skip to content

Instantly share code, notes, and snippets.

@zacscott
Last active April 27, 2020 16:01
Show Gist options
  • Select an option

  • Save zacscott/b9b032772ca7e1008ae93e9a35a85eac to your computer and use it in GitHub Desktop.

Select an option

Save zacscott/b9b032772ca7e1008ae93e9a35a85eac 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: Provides the <code>FragmentCache</code> helper class
* Version: 1.2
* Author: Zachary Scott
*/
namespace zacscott;
/**
* Simple fragment cache using WP transients. Based off:
* https://gist.github.com/markjaquith/2653957
*
* @author Zachary Scott <zac@zacscott.net>
*/
class FragmentCache {
const GROUP = 'cache-fragments';
private $key;
private $ttl;
public function __construct( $key, $ttl ) {
$this->key = $key;
$this->ttl = $ttl;
}
public function output() {
$output = get_transient( $this->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;
}
}
public function store() {
$output = ob_get_flush(); // Also flushes the buffers
set_transient( $this->key(), $output, $this->ttl );
echo "<!-- /frag {$this->key} -->\n";
}
// Returns the cache key
private function key() {
$key = $this->key;
// Whether we are on a secure connection
$is_https = (
isset( $_SERVER['HTTPS'] ) &&
! empty( $_SERVER['HTTPS'] ) &&
$_SERVER['HTTPS'] !== 'off'
) || (
isset( $_SERVER['SERVER_PORT'] ) &&
$_SERVER['SERVER_PORT'] == 443
);
// Make unique if is HTTPS v HTTP
if ( $is_https ) {
$key = $key . '_https';
}
// Has to an acceptable length
return 'frag_' . md5( $key . self::GROUP );
}
}
@limsoke
Copy link
Copy Markdown

limsoke commented Apr 27, 2020

thanks, need this

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment