nilcms file类 简单文件缓存实现

来源:互联网 发布:qq宠物 知乎 编辑:程序博客网 时间:2024/05/21 17:28

实现简单的文件缓存,参照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;    }}

结束

调度

原创粉丝点击