<?php
 
/*
 
Copyright 2005 V. Yanson <admin@urbansoot.net>
 
You can freely use this class anywhere as long as you keep this note untouched.
 
Implementation:
 
$cache = new cache();
$my_variable = array();
$my_variable['once'] = 1;
$my_variable['two'] = 2;
$my_variable[3] = 'three';
$my_variable['next level'] = array("_one" = 1);
 
$cache->save(md5("my_variable"), $my_variable);
print_r($cache->get(md5("my_variable")));
 
*/
 
class cache
{
    function cache($life = 3600, $dir = "./cache")
    {
        $this->cache_life = $life;
        $this->cacheFolder = $dir;
    }
    
    function save($uid, $value)
    {
        // remove previously saved value
        $dh = opendir($this->cacheFolder);
        while (false !== ($file = readdir($dh)))
        {
            if (preg_match("/\." . $uid . "\.([0-9])*\.txt/", $file))
            {
                unlink($this->cacheFolder . "/" . $file);
            }
        }
        
        // save
        $file = $this->cacheFolder . "/." . $uid . "." . time() . ".txt";
        $fp = fopen($file, "w");
        
        fputs($fp, serialize($value));
        
        fclose($fp);
    }
    
    function get($uid)
    {
        // find the record
        $dh = opendir($this->cacheFolder);
        while (false !== ($file = readdir($dh)))
        {
            if (preg_match("/\." . $uid . "\.([0-9])*\.txt/", $file))
            {
                $exp = explode(".", $file);
                $time = $exp[2];
                
                if ((time() - $time) < $this->cache_life)
                {
                    $value = unserialize(file_get_contents($this->cacheFolder . "/" . $file));
                } else {
                    // too old. remove it
                    unlink($this->cacheFolder . "/" . $file);
                    $value = false;
                }
                
                return $value;
                
                // we dont need to search any more
                break;
            }
        }
        
        return false;
    }
    
    function clear()
    {
        // delete everythign from cache folder
        $dh = opendir($this->cacheFolder);
        while (false !== ($file = readdir($dh)))
        {
            if ($file !== "." && $file !== "..")
                unlink($this->cacheFolder . "/" . $file);
        }
    }
}
 
?>