andybeak
2/12/2015 - 10:00 AM

Cache

<?php

/**
 * Class Cache
 *
 * Facade class to wrap the basic cache functions we use to the Memcached extension so that 
 * we can decide to use a different cache and just rewrite this file instead of changing 
 * all the usages.
 *
 * @author Andy Beak
 */

class Cache
{
    private static $mc;

    private static $log;

    public static function initConnection()
    {
        self::$mc = new Memcached();

        self::$mc->addServer("localhost", 11211);
    }

    public static function getInstance()
    {
        if(!is_object(self::$mc) || get_class(self::$mc) !== 'Memcached')
        {
            self::initConnection();
        }

        return self::$mc;
    }

    public static function add($key, $value, $expiration = 600)
    {
        $mc = self::getInstance();

        $mc->add($key, $value, $expiration);
    }

    public static function flush($delay =0)
    {
        $mc = self::getInstance();

        $flushResult = $mc->flush($delay);

        return $flushResult;
    }


    public static function get($key)
    {
        $mc = self::getInstance();

        $cacheReturn = $mc->get($key);

        if(false == $cacheReturn)
        {
            $cacheHitResult = 'missed';
        }
        else
        {
            $cacheHitResult = 'hit';
        }

        return $cacheReturn;
    }

    public static function status()
    {
        $mc = self::getInstance();

        if (get_class($mc) == 'Memcached')
        {
            $stats = $mc->getStats();

            $stats = reset($stats);      // assume we are only running one server!

            $stats['status'] = 'OK';

            return $stats;
        }
        else
        {
            return ['status' => 'Cannot connect'];
        }
    }

    public static function setLog(Log $log)
    {
        self::$log = $log;
    }
}