Faster bootstrap with object cache in memory

When WordPress loads something, it first looks things up in its object cache. If you have posts or other permanent information that should not be loaded with every single visit, then the object cache is your performance boost. A “object-cache.php” file allows you to override the usual object cache.Read the more up to date and famous one afterwards!
Everything cool and wrong about upcoming WordPress 4.7
Open in new tab for later

Simple Memcache example

A good way to store information in the memcache is to extend the WP_Object_Cache class and store everything you need while destructing the object.

The “wp-content/object-cache.php” just needs a few lines like this:

<?php

$_GLOBALS['wp_object_cache'] = new My_Object_Cache();

And the actual class needs to look like this:

class My_Object_Cache extends \WP_Object_Cache {
  private function memcache() {
    static $memcache_obj =
      memcache_connect('memcache_host', 11211);

      return $memcache_obj;
  }

  // try memcache before WP cache
  public function get( $key, $group = 'default', $force = false, &$found = null ) {
    $var = memcache_get(
      $this->memcache(),
      $this->get_hash( $group, $key )
    );

    if ( $var ) {
       // found in memcache => reuse
       return $var;
    }

    // not found => delegate
    return parent::get( $key, $group, $force, $found );
  }

  // Define what shall persist in the cache
  protected function get_cachable() {
    return array(
      'post' => array(
        123,
      ),
    )
  }

  // Create a UID for the cache entry
  protected function get_hash( $group, $id ) {
    return $group . '_' . $id;  // might be enough
  }

  // Finally do it
  public function __destruct() {
    // get all persistable and do so
    foreach ( $this->get_cachable() as $group => $all_ids ) {

      foreach ( $all_ids as $id ) {
        // store in memcache
        memcache_set(
          $this->memcache(),

          // where to store
          $this->get_hash( $group, $id ),

          // what to store
          $this->get( 123, 'post' ),

          // compressed (default)
          MEMCACHE_COMPRESSED,

          // expire time
          WEEK_IN_SECONDS
        );
      }

    }

  }
}

You can add other heuristics to store often used things automatically. Furthermore these are just the basics, so please add something to flush all the cache. Maybe by using the actions “clean_post_cache”, “clean_page_cache”, “clean_attachment_cache”, “clean_user_cache”, “clean_comment_cache”, “clean_object_term_cache” or “clean_term_cache”.

Leave a Reply

Your email address will not be published. Required fields are marked *