PHP代碼篇(八)--php實現文件緩存的讀寫

  說,近期接手的論壇項目,由於對於代碼,不是特別熟悉,有個地方須要用到緩存,因此寫了一個基於file_put_contents函數文件的寫入和fopen函數文件的打開,實現的一個文件緩存,具體能夠用,可是對於高併發,多用戶同時訪問,不知道會如何。php

  若是有大佬看見這篇博客,但願給些意見或評論。主要是,phpwind這個論壇的緩存確實不太熟悉,本身寫的緩存這個,其實就是一個文件讀寫而已,正真的緩存,但願大佬們給個大體的說道。json

  下面是代碼正文:緩存

<?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);
相關文章
相關標籤/搜索