<?php
class cache {
//cache path
private $cache_path = './cache/';
/**
* static method
* can refer to static
*
* @access public
* @return static obiect
*
*/
public static function factory()
{
return new cache;
}
/**
* methos allows you to save cache
*
* @access public
* @param string $name - filename of cache
* @param mixed $value - value of cache
* @param integer $time - time expired cache
*
*/
public function save( $name, $value, $time)
{
//if is all ok
if( $this -> _findCache( $name) == false)
{
$time = $time + time();
$name = $name . '~' . $time;
file_put_contents( $this -> cache_path . $name, serialize( $value));
}
//if time expired
elseif( $this -> expired( $name) < time())
{
$this -> flush( $name);
$this -> save( $name, $value, $time);
}
//if cache exists and time no expired
else
{
echo 'cach exists';
}
}
/**
* load cache
*
* @access public
* @param string $name - filename of cache
*
*/
public function load( $name)
{
if( $this -> state( $name) === true)
{
return unserialize( file_get_contents( $this -> _findCache( $name)));
}
else
{
return false;
}
}
/**
* delete cache
*
* @access public
* @param string $name - filename of cache
*
*/
public function flush( $name = false)
{
if( $name == true)
{
//delete one selected cache
if( file_exists( $this -> _findCache( $name)))
{
$this -> _findCache( $name);
unlink( $this -> _findCache( $name));
}
//delete all cache
else
{
echo 'file no\'t exists';
}
}
else
{
$files = glob( $this -> cache_path . '*');
foreach( $files as $item)
{
unlink( $item);
}
}
}
/**
* return expired time to left
*
* @access public
* @param string $name - filename of cache
*
*/
public function expired( $name)
{
$expired = substr( strstr($this -> _findCache( $name), '~'), 1);
return ($expired > time()) ? $expired - time() : false;
}
/**
* check state
*
* @access private
* @param string $name - filename of cache
*
*/
private function state( $name)
{
if( $this -> _findCache( $name) == true)
{
$r = explode('~', $this -> _findCache( $name)); //0 = filename; 1 = time
if( $r[1] > time())
{
return true;
}
else
{
return false;
}
} else { return false; }
}
/**
* find all name of cache
*
* @accessprivate
* @param string $name - filename of cache
*
*/
private function _findCache( $name)
{
$files = glob( $this -> cache_path . $name . '~*');
if( $files == false)
{
return false;
}
else
{
return $files[0];
}
}
}