Skip to content

Instantly share code, notes, and snippets.

@zacscott

zacscott/object-cache.php

Last active Jun 15, 2020
Embed
What would you like to do?
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
You can’t perform that action at this time.