美文网首页
Lumen(laravel轻量级)封装redis分页类

Lumen(laravel轻量级)封装redis分页类

作者: 快乐的bug制造者 | 来源:发表于2018-02-02 15:34 被阅读77次
<?php

namespace Framework\Lib;

use Illuminate\Http\Request;

class CatcheModel {
    /**
     * 列表数据
     * 从redis读取,如果redis无,则读取静态文件,并写入redis
     * @param string $key       key值
     * @param int $page     当前页数
     * @param int $size     每页显示条目
     * @return boolean|array
     */
    public static function get_page_list($key,$page = 0, $size = 0) {
        /*
         * 从redis或file中读取分页的数据
        * 返回:array
        */
        if ($key=="") {
            return "";
        }

        // 获取redis内容
        $data = self::get_cache_data($key);


        $result = json_decode($data,true);

        if(!EMPTY($result->data)) {
            $tmp = self::get_page_data($result->data, $page, $size);
        }
        else {
            return $data;
        }

        $result->data = $tmp;

        return json_encode($result);
    }


    //在缓存中读取json内容
    public static function get_cache_data($key)
    {
        $data ='';

        if (empty($key) || $key=="") {
            return null;
        }

        $redis = app('redis')->connection('shan');

        $datas = $redis->get($key);
        if(!empty($datas))//缓存里查找该内容
        {
            $data = $datas;
        }
        if($datas !="")
            return json_decode($data,true);
        else
            return null;
    }


    /**
     * 计算获取数组中的分页数据
     * @param array $data   数据集合
     * @param int   $page   当前页数
     * @param int   $size   每页显示条目
     * @return boolean|array
     */
    public static function get_page_data($data = null, $page = 0, $size = 0) {
        if (empty($data) || !is_array($data)) {
            return null;
        }

        if (!empty($page) && !empty($size)) {
            $count = count($data);  // 计算数组元素数目
            $start = (($page - 1) * $size);  // 开始位,从0开始
            $end = ($start + $size) > $count ? $count : ($start + $size); // 结束位,最大元素数目

            for ($i = $start; $i < $end; $i++) {
                $result[] = $data[$i];
            }
        } else {
            $result = $data;
        }


        return $result;
    }

    /*
     * 将指定数据以指定key值写入redis缓存中
     */
    public static function save_cache_data($key,$data,$expire=86400) {
        $redis = app('redis')->connection('default');
        $redis->set($key, $data); #生成缓存
        $redis->expire($key, $expire);
    }
}

相关文章

网友评论

      本文标题:Lumen(laravel轻量级)封装redis分页类

      本文链接:https://www.haomeiwen.com/subject/wolezxtx.html