PHP代码篇(八)--php实现文件缓存的读写

  说,近期接手的论坛项目,因为对于代码,不是特别熟悉,有个地方需要用到缓存,所以写了一个基于file_put_contents函数文件的写入和fopen函数文件的打开,实现的一个文件缓存,具体可以用,但是对于高并发,多用户同时访问,不知道会如何。

  如果有大佬看见这篇博客,希望给些意见或评论。主要是,phpwind这个论坛的缓存确实不太熟悉,自己写的缓存这个,其实就是一个文件读写而已,正真的缓存,希望大佬们给个大致的说道。

  下面是代码正文:

<?php 
/**
 * 生成一个文件缓存
 * User:WuYan
 * Time:2020.5.12
 */

class cache 
{
    const CACHE_PATH = './data/file/';//缓存路径
    const CACHE_TYPE = '.md';//缓存文件后缀

    //创建静态私有的变量保存该类对象
    static private $instance;

    //防止使用new直接创建对象
    private function __construct(){}

    //防止使用clone克隆对象
    private function __clone(){}
    
    static public function getInstance()
    {
        //判断$instance是否是Singleton的对象,不是则创建
        if (!self::$instance instanceof self) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * 设置文件缓存
     * @param [type] $key 缓存键名 string
     * @param [type] $value 缓存键值 array
     * @param integer $time 缓存时间 s
     * @return [booleans]
     */
    public static function setCache($key, $value, $time = 0)
    {
        if (!is_array($value)) {
            return false;
        }
        //创建缓存目录
        if (!file_exists(self::CACHE_PATH)) {
            $mode = intval('0777', 8);
            mkdir(self::CACHE_PATH, $mode, true);
        }
        $data = [
            'time' => $time ? time() + $time : 0,
            'data' => $value,
        ];
        //写入文件,重写模式
        $result = file_put_contents(self::CACHE_PATH.'/'.$key.self::CACHE_TYPE, json_encode($data));
        if ($result) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 读取缓存文件内容
     * @param [type] $key 缓存键名 string
     * @return [array]
     */
    public static function getCache($key)
    {    //文件路径
        $file_path = self::CACHE_PATH.$key.self::CACHE_TYPE;
        if (file_exists($file_path)) {
            //打开文件
            $fp = fopen($file_path,"r");
            //指定读取大小,这里把整个文件内容读取出来
            $string = fread($fp,filesize($file_path));
            if (!$string) {
                return false;
            }
            $array = json_decode($string, true);
            if (empty($array['data'])) {
                return false;
            }
            //判断是否过期
            if ($array['time']) {
                if ($array['time'] > time()) {//未过期
                    $result_data = $array['data'];
                } else {
                    //关闭文件并删除
                    fclose($fp);
                    unlink($file_path);
                    return false;
                }
            } else {//未设置时效
                $result_data = $array['data'];
            }
            //关闭文件
            fclose($fp);
            return $result_data;
        } else {
            return false;
        }
    }
}

调用的话,直接

cache::setCache('pw_area',['100'=>'北京市','101'=>'上海市'],3600);

猜你喜欢

转载自www.cnblogs.com/camg/p/12880298.html
今日推荐