Skip to content

Instantly share code, notes, and snippets.

@zacscott
Last active June 15, 2020 00:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zacscott/5e10c1e97a8fb6928bdcf8af1457fefd to your computer and use it in GitHub Desktop.
Save zacscott/5e10c1e97a8fb6928bdcf8af1457fefd to your computer and use it in GitHub Desktop.
Custom object cache for WordPress with some logic for selectively disabling it for certain URLs.
<?php
/**
* Plugin Name: Object Cache
* Description: Object cache backend - uses APC for local development, Redis or Memcached for prod/staging.
* Version: 3.0
* Author: The Code Company
* Author URI: http://thecode.co
*
* @package thecodeco
*/
/**
* Whether the object cache should be enabled.
*
* @var boolean
*/
$object_cache_enabled = true;
// Determine if we are on a URL which is has the object cache disabled.
if ( defined( 'OBJECT_CACHE_BLACKLIST_URLS' ) ) {
// phpcs:disable
$request_uri = isset( $_SERVER['REQUEST_URI'] ) ? $_SERVER['REQUEST_URI'] : '';
$request_path = parse_url( $request_uri, \PHP_URL_PATH );
// phpcs:enable
foreach ( OBJECT_CACHE_BLACKLIST_URLS as $blacklist_regex ) {
if ( preg_match( $blacklist_regex, $request_uri ) ) {
$object_cache_enabled = false;
break;
}
}
}
// Set object cache disabled via constant.
if ( defined( 'OBJECT_CACHE_DISABLE' ) && OBJECT_CACHE_DISABLE ) {
$object_cache_enabled = false;
}
// Load the appropriate object cache.
if ( $object_cache_enabled ) {
if ( defined( 'OBJECT_CACHE_USE_MEMCACHE' ) && OBJECT_CACHE_USE_MEMCACHE ) {
header( 'X-ObjectCache: memcached' );
require dirname( __FILE__ ) . '/memcached-object-cache.php';
} else {
header( 'X-ObjectCache: apc' );
require dirname( __FILE__ ) . '/apc-object-cache.php';
}
} else {
header( 'X-ObjectCache: disabled' );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment