Skip to content

4.缓存类

mi pro edited this page Apr 28, 2018 · 3 revisions

缓存类

/**
 * 缓存驱动
 */
class Cache implements \Itxiao6\Database\CacheInterface
{
    /**
     * 生成缓存的key
     * @param $keyword
     * @return string
     */
    public function make_name($keyword){
        return 'databases_'.$keyword;
    }

    /**
     * 设置值
     * @param $name
     * @param $value
     * @param $time
     * @return bool|int
     */
    public function set($name,$value,$time){
        return file_put_contents(__DIR__.'/data/'.$name.'txt',['data'=>serialize($value),'invalid'=>time()+$time]);
    }

    /**
     * 获取值
     * @param $name
     * @return mixed
     * @throws \Exception
     */
    public function get($name){
        if(file_exists(__DIR__.'/data/'.$name.'txt') && is_file(__DIR__.'/data/'.$name.'txt')){
            $data = unserialize(file_get_contents(__DIR__.'/data/'.$name.'txt'));
            if((!isset($data['invalid'])) || $data['invalid'] < time()){
                unlink(__DIR__.'/data/'.$name.'txt');
                throw new \Exception('暂无数据');
            }else{
                return isset($data['data'])?$data['data']:null;
            }
        }else{
            throw new \Exception('暂无数据');
        }
    }
    /**
     * 判断缓存连接 是否通畅
     * @return bool
     */
    public function ping()
    {
        return true;
    }
    
    /**
     * 重新连接
     * @return bool
     */
    public function reconnect()
    {
        return true;
    }

    /**
     * 记住数据
     * @param string $name
     * @param \Closure|null $callback
     * @param int $time
     * @return mixed
     * @throws \Exception
     */
    public function remember($name,$callback = null,$time = 0){
        try{
            # 获取缓存的数据
            $data = $this -> get($name);
        }catch (\Exception $exception){
            if($exception -> getMessage() == '暂无数据'){
                # 获取数据
                $data = $callback();
                # 存储数据
                $this -> set($name,$data,$time);
                # 返回数据
                return $data;
            }else{
                # 抛出其他异常
                throw $exception;
            }
        }
    }
}
Clone this wiki locally