PHP 实现文件缓存数组等数据

PHP  

PHP 有Redis,Memcache等高速缓存,但是低端服务器可能就没有这些配置了,我们可以尝试着把经常用到的数据(如:数组、导航条、页面底部信息等)缓存到文件中,这样就能“快速的”获取相应的信息了。


以下是尝试的一部分代码:


// 自定义缓存
class YCache
{
    // 从文件读取缓存
    // 将 json 转换为普通格式
    // key 要读取的键值
    public static function get($key ,$options)
    {
        $reval = '';
        $path = __DIR__ . './cache/';
        if (is_array($options))
        {
            $baseOptions = self::setOptions([
                                'path' => $path,
                            ] ,$options);
            $path = $baseOptions['path'];
        }
        $file_name = $path.md5($key).'.txt';
        //echo $file_name;die();
        if (file_exists($file_name))
            $reval = json_decode(file_get_contents($file_name),true);
        else
            $reval = null;
        return $reval;
    }
    // 写入文件缓存
    // 用 json 格式保存内容
    // key 要保存的键值
    // value 要保存的值
    public static function set($key ,$value ,$options)
    {
        $path = __DIR__ . './cache/';
        if (is_array($options))
        {
            $baseOptions = self::setOptions([
                                'path' => $path,
                            ] ,$options);
            $path = $baseOptions['path'];
        }
        $file_name = $path.md5($key).'.txt';
        if(!file_exists(dirname($file_name)))
            mkdir(dirname($file_name), 0555);
        //echo $file_name;die();
        file_put_contents($file_name , json_encode($value));
    }
    // 根据传入的参数更改相应的设定
    // baseOptions 基础设定数组
    // options 传入的设定数组
    public static function setOptions($baseOptions ,$options)
    {
        if (! is_null($options['subPath']))
            $baseOptions['path'] .= $options['subPath'] .'/';
        return $baseOptions;
    }
}


测试代码如下:



$arr = [
    1 => [
        'name' => '帮助',
        'parent_id' => 0,
        'namealias' => 'help',
        'keywords' => 'chm,helper'
    ],
    2 => [
        'name' => '经验',
        'parent_id' => 1,
        'namealias' => 'exp',
        'keywords' => 'exp,helper'
    ],
];
// 将数组存储到文件中
YCache::set('category_menu_with_zero',$arr ,['subPath' => 'category']);


读取数据:



$re = YCache::get('category_menu_with_zero' ,['subPath' => 'category']);
echo $re[2]['name'];


输出结果:

经验

时间:2017年05月03日    作者:孟德    分类:后端   浏览:2763    评论:0

链接地址:https://www.abclogs.com/backend_php_cache_array_code_variable.html

评论列表

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。