PHP CACHE EXAMPLE WITH TIMEOUT

<?php
// this is our base interface for cache class

interface CacheDriver
{
    public function get($key, $timeout = null, callable $callback = null);

    public function set($key, $value, $timeout = null);

    public function delete($key);

    public function deleteAll();

    public function deleteExpired();

    public function deleteExpiredByTimeout($timeout);

    public function deleteExpiredByKey($key);

    public function deleteExpiredByKeyTimeout($key, $timeout);
}


/**
 * Class Cache
 * static cache
 * save data in file
 * set file names as md5
 * use directory structure to save data
 * define timeout limit for cache files and if exceeded delete file
 * store cache as serialized time and data array
 *
 */
class FileCache implements CacheDriver
{

    /**
     * @var string
     */
    private static $cache_dir = 'cache/';

    /**
     * @var int
     */
    private static $cache_timeout = 3600;

    /**
     * @var string
     */
    private static $cache_ext = '.cache';

    /**
     * @param $key
     * @param int $timeout
     * @param callable $callback
     * @return bool
     * @description get data from cache by key
     */
    public function get($key, $timeout = null, callable $callback = null)
    {
        $file = self::$cache_dir . $key . self::$cache_ext;
        if (file_exists($file)) {
            $data = unserialize(file_get_contents($file));
            if (time() - $data['time'] < $timeout) {
                return $data['data'];
            }
        }

        if (is_callable($callback)) {
            $data = call_user_func($callback);
            $this->set($key, $data, $timeout);
            return $data;
        }

        unlink($file);

        return false;
    }

    /**
     * @param $key
     * @param $data
     * @return bool
     * @description set data and timeout to cache by key
     */

    public function set($key, $data, $timeout = null)
    {
        $file = self::$cache_dir . $key . self::$cache_ext;
        $data = array('time' => time(), 'data' => $data);
        file_put_contents($file, serialize($data));
        return true;
    }

    /**
     * @param $key
     * @return bool
     * @description delete cache by key
     */
    public function delete($key)
    {
        $file = self::$cache_dir . $key . self::$cache_ext;
        if (file_exists($file)) {
            unlink($file);
            return true;
        }
        return false;
    }

    /**
     * @return bool
     * @description delete all cache
     */
    public function deleteAll()
    {
        $files = glob(self::$cache_dir . '*' . self::$cache_ext);
        foreach ($files as $file) {
            unlink($file);
        }
        return true;

    }

    /**
     * @return bool
     * @description delete expired cache
     */
    public function deleteExpired()
    {
        $files = glob(self::$cache_dir . '*' . self::$cache_ext);
        foreach ($files as $file) {
            $data = unserialize(file_get_contents($file));
            if (time() - $data['time'] > self::$cache_timeout) {
                unlink($file);
            }
        }
        return true;

    }

    /**
     * @return bool
     * @description delete expired cache
     */
    public function deleteExpiredByTimeout($timeout)
    {
        $files = glob(self::$cache_dir . '*' . self::$cache_ext);
        foreach ($files as $file) {
            $data = unserialize(file_get_contents($file));
            if (time() - $data['time'] > $timeout) {
                unlink($file);
            }
        }
        return true;
    }

    /**
     * @return bool
     * @description delete expired cache
     */

    public function deleteExpiredByKey($key)
    {
        $file = self::$cache_dir . $key . self::$cache_ext;
        if (file_exists($file)) {
            $data = unserialize(file_get_contents($file));
            if (time() - $data['time'] > self::$cache_timeout) {
                unlink($file);
            }
        }
        return true;
    }

    /**
     * @return bool
     * @description delete expired cache
     */
    public function deleteExpiredByKeyTimeout($key, $timeout)
    {
        $file = self::$cache_dir . $key . self::$cache_ext;
        if (file_exists($file)) {
            $data = unserialize(file_get_contents($file));
            if (time() - $data['time'] > $timeout) {
                unlink($file);
            }
        }
        return true;
    }
}


class Cache extends FileCache
{
    public function __construct()
    {
        parent::__construct();
    }
}

$cache = new Cache();
$result = $cache->get("test", DEFAULT_CACHE_TIMEOUT, function () {
    return "data of cache";
});

Leave a Reply

Your email address will not be published.