nilcms file類 簡單文件緩存實現

實現簡單的文件緩存,參照CI的部分設計,在這裏記錄一下子。

class File
{
    const CACHE_PATH = 'nil_file_cache';
 
    /*其他函數省略了*/
 
    /**
     * 獲取緩存文件.
     *
     * @param string  $key  緩存名.
     *
     * @return string|false
     */
    private static function getCacheFile($key)
    {
        return (empty($key))
            ? false
            : NIL_DATA_PATH.DIRECTORY_SEPARATOR.self::CACHE_PATH.DIRECTORY_SEPARATOR.$key.'.bin';
    }
 
    /**
     * 刪除緩存文件.
     * 存在就刪除
     *
     * @param string  $key  緩存名.
     *
     * @return null
     */
    public static function cacheDelete($key)
    {
        /*緩存文件*/
        $file = self::getCacheFile($key);
 
        if( is_file($file) )
        {
            @unlink($file);
        }
    }
 
    /**
     * 獲取緩存.
     *
     * @param string  $key  緩存名.
     *
     * @return mixed|false 結果
     */
    public static function cacheGet($key)
    {
        /*緩存文件*/
        $file = self::getCacheFile($key);
        if( ! is_file($file) )
        {
            return false;
        }
 
        /*讀取*/
        $data = @file_get_contents($file);
        if($data === false)
        {
            return false;
        }
         
        /*序列化*/
        $data = @unserialize($data);
 
        /*定義基本的值 未過期*/
        if( ! isset($data['ttl'],$data['time'],$data['data']) || ($data['ttl'] > 0 && time() >  $data['time'] + $data['ttl']) )
        {
            @unlink($file);
            return false;
        }
 
        /*返回*/
        return $data['data'];
    }
 
    /**
     * 生成緩存.
     *
     * @param string  $key  緩存名.
     * @param mixed   $data 數據.
     *
     * @return bool 是否成功
     */
    public static function cacheSave($key, $data, $time = 0)
    {
        /*路徑*/
        $path = self::getCacheFile($key);
        if(false === $path)
        {
            return false;
        }
 
        /*組合數據*/
        $d = [
            'time'  => time(),
            'ttl'   => $time,
            'data'  => $data
        ];
 
        /*寫入數據*/
        if(self::write($path, serialize($d)))
        {
            @chmod($path, 0640);
            return true;
        }
         
        return false;
    }
}

結束

調度

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章