具体要求:建一张表,字段可以有key,value,cachetime,ctime封装一个把mysql当作kvdb的类来操作这个表,像memcache一样,有set,get,delete方法等。要求用到工厂模式,单件模式,适配器模式。
我建的表:
CREATE TABLE IF NOT EXISTS `mysql_cache_demo` (
`cache_key` varchar(255) NOT NULL,
`cache_value` text NOT NULL,
`cache_time` int(11) NOT NULL COMMENT '缓存时间',
`create_time` int(11) NOT NULL COMMENT '创建时间',
`update_time` int(11) NOT NULL COMMENT '更新时间',
PRIMARY KEY (`cache_key`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
当然只是一个练习吧,Mysql做缓存系统肯定不是什么好办法,代码呢也测试通过都(代码贴上来排版全乱了,就酱紫吧,能大概看下就行了):
class Cache
{
private static $instance = array();
/**
* 缓存实例化的工厂方法并且确保单例
*/
public static function getInstance( $type,$options=array()){
$type = strtolower(trim($type));
if(isset(self::$instance[$type])){
return self::$instance[$type];
}
$class = 'Cache'.ucwords($type);
//class_exists 前提是已经有了自动载入机制
if(class_exists($class)){
$cache = new $class($options);
self::$instance[$type] = $cache;
}else{
throw new Exception('error cache type');
}
return $cache;
}
}
/**
* 封装适配器接口规范
*/
interface CacheInterface
{
function set($name, $value, $expire = null);
function get($name);
function delete($name);
}
abstract class CacheAbstract implements CacheInterface
{
//设置默认的<