zoukankan      html  css  js  c++  java
  • thinkphp6.0封装数据库及缓存模型

    项目中的thinkphp6.0appcommonModel.php

      1 <?php
      2 /**
      3  * 数据库及缓存模型
      4  */
      5 namespace appcommon;
      6 
      7 use appindexserverRedisServer;
      8 use thinkdbBaseQuery;
      9 use thinkfacadeDb;
     10 use thinkfacadeLog;
     11 
     12 class Model
     13 {
     14     protected $name;
     15 
     16     /** 查询多条数据信息(批量查询方法), 缓存中未找到时去数据库查询
     17      * @param $ids
     18      * @return array
     19      */
     20     public function getCacheList($ids)
     21     {
     22         // 整理查询的数据, 并存入 $key
     23         $keys = [];
     24         foreach ($ids as $id) {
     25             if($id)
     26             {
     27                 $keys[$id] = $id;
     28             }
     29         }
     30         if (empty($keys)) {
     31             return [];
     32         }
     33 
     34         // 准备结果集
     35         $result = [];
     36 
     37 
     38         /** 在Redis中查询数据
     39          * @var Redis $redis
     40          */
     41         $redis = Instance::getInstance(RedisServer::class);
     42         if ($redis) {
     43             //创建管道,批量获取
     44             $pip = $redis->pipeline();
     45             foreach ($keys as $id) {
     46                 $pip->hGetAll(static::class . ':' . $id);
     47             }
     48             if ($caches = $pip->exec()) {
     49                 foreach ($caches as $value) {
     50                     if ($value) {
     51                         // 在$key中删除掉已查询到的数据
     52                         unset($keys[$value['id']]);
     53                         $result[$value['id']] = $value;
     54                     }
     55                 }
     56             }
     57         }
     58 
     59         // 如果 $keys 不为空, 则表示有数据未从缓存中查询到, 在 mysql 中进行查询并缓存到Redis
     60         if ($keys) {
     61             foreach ($this->query()->whereIn('id', array_values($keys))->cursor() as $item) {
     62                 $redis->hMSet(static::class . ':' . $item['id'], $item);
     63                 $redis->expire(static::class . ':' . $item['id'], 60); //有效期10分钟
     64                 $result[$item['id']] = $item;
     65             }
     66         }
     67         return $result;
     68     }
     69 
     70 
     71     /** 查询单条数据信息, 缓存中未找到时去数据库查询
     72      * @param $id
     73      * @param null $showKey
     74      * @return mixed|null
     75      */
     76     public function getCacheInfo($id, $showKey = null)
     77     {
     78         $redis = Instance::getInstance(RedisServer::class);
     79         if ($redis) {
     80             if ($cache = $redis->hGetAll(static::class . ':' . $id)) {
     81                 return $showKey ? $cache[$showKey] : $cache;
     82             }
     83         }
     84         $data = $this->query()->where('id', $id)->find();
     85         if ($data) {
     86             $redis->hMSet(static::class . ':' . $id, $data);
     87             $redis->expire(static::class . ':' . $id, 60); //有效期10分钟
     88             return $showKey ? $data[$showKey] : $data;
     89         }
     90         return null;
     91     }
     92 
     93 
     94     /** 查询多条数据信息, 缓存中未找到时去数据库查询
     95      * @param $ids
     96      * @return array
     97      */
     98     public function getCacheDataList($ids)
     99     {
    100         $result = [];
    101         foreach ($ids as $id) {
    102             $result[$id] = $this->getCacheInfo($id);
    103         }
    104         return $result;
    105     }
    106 
    107 
    108     /** 根据ID执行单条数据查询, 并存储到Redis
    109      * @param $id
    110      * @return null
    111      */
    112     public function setCacheInfo($id)
    113     {
    114         $redis = Instance::getInstance(RedisServer::class);
    115         $data = $this->query()->where('id', $id)->find();
    116         if ($data) {
    117             $redis->hMSet(static::class . ':' . $id, $data);
    118             $redis->expire(static::class . ':' . $id, 600); //有效期10分钟
    119             return $data;
    120         }
    121         return null;
    122     }
    123 
    124 
    125 
    126     /** 数据库中根据ID查询信息(不经过缓存)
    127      * @param $id
    128      * @param string $field
    129      * @return mixed
    130      */
    131     public function getById($id, $field = '*')
    132     {
    133         $where = [
    134             'id' => $id,
    135             'is_delete' => 0
    136         ];
    137         return $this->query()->where($where)->field($field)->find();
    138     }
    139 
    140 
    141 
    142     /** 数据库中根据ID查询用户信息(不经过缓存)
    143      * @param $id
    144      * @param string $field
    145      * @return mixed
    146      */
    147     public function getByUserId($userId)
    148     {
    149         $where = [
    150             'user_id' => $userId,
    151             'is_delete' => 0
    152         ];
    153         return $this->query()->where($where)->find();
    154     }
    155 
    156     /**
    157      * @return BaseQuery
    158      */
    159     public function query()
    160     {
    161         return Db::name($this->name);
    162     }
    163 
    164 
    165 
    166     /** 创建$query对象
    167      * @return 	hinkModel
    168      */
    169     public static function createQuery($field = '*', $where = null, $order = null)
    170     {
    171         $query = Instance::getInstance(static::class)->query()->field($field);
    172         if ($where) {
    173             $query->where($where);
    174         }
    175         if ($order) {
    176             $query->order($order);
    177         }
    178         return $query;
    179     }
    180 
    181 
    182     /** 创建查询$query 并添加查询条件, (where, order, limit, field)
    183      * 不直接调用, 只通过该类下的 select等方法调用
    184      * @param null $where
    185      * @param array $order
    186      * @param null $limit
    187      * @param null $field
    188      * @return BaseQuery
    189      */
    190     public function createSelect($where = null, $order = [], $limit = null, $field = null)
    191     {
    192         $query = $this->query();
    193         if ($where) {
    194             $query->where($where);
    195         }
    196         if ($field) {
    197             $query->field($field);
    198         }
    199         if ($order) {
    200             foreach ($order as $key => $value) {
    201                 $query->order($key, $value);
    202             }
    203         }
    204         if ($limit) {
    205             if (is_integer($limit)) {
    206                 $query->limit($limit);
    207             } else {
    208                 $query->limit($limit[0], $limit[1]);
    209             }
    210         }
    211         return $query;
    212     }
    213 
    214 
    215     /** 多条数据查询方法
    216      * @param null $where
    217      * @param array $order
    218      * @param null $limit
    219      * @param null $format
    220      * @param null $field
    221      * @return array
    222      */
    223     public function select($where = null, $order = [], $limit = null, $format = null, $field = null)
    224     {
    225         $result = [];
    226         $query = $this->createSelect($where, $order, $limit, $field);
    227         if ($dataList = $query->select()) {
    228             foreach ($dataList as $value) {
    229                 $result[] = $format ? call_user_func_array($format, [$value]) : $value;
    230             }
    231         }
    232         return $result;
    233     }
    234 
    235 
    236     /** 单条数据查询方法
    237      * @param null $where
    238      * @param array $order
    239      * @param null $limit
    240      * @param null $field
    241      * @return mixed
    242      */
    243     public function find($where = null, $order = [], $limit = null, $field = null)
    244     {
    245         return $this->createSelect($where, $order, $limit, $field)->find();
    246     }
    247 
    248     public function selectIndex($where = null, $order = [], $limit = null, $format = null, $field = null)
    249     {
    250         $result = [];
    251         $query = $this->createSelect($where, $order, $limit, $field);
    252         if ($dataList = $query->select()) {
    253             foreach ($dataList as $value) {
    254                 $result[$value['id']] = $format ? call_user_func_array($format, [$value]) : $value;
    255             }
    256         }
    257         return $result;
    258     }
    259 
    260 
    261     /** 根据ID删除数据(软删除)
    262      * @param $id
    263      * @return mixed
    264      */
    265     public function deleteById($id)
    266     {
    267         return $this->query()->where(['id' => $id])->update(['is_delete' => 1]);
    268     }
    269 
    270 
    271     /** 根据where条件删除数据
    272      * @param $where
    273      * @return mixed
    274      */
    275     public function deleteByWhere($where)
    276     {
    277         return $this->query()->where($where)->delete();
    278     }
    279 
    280 
    281     /** 插入数据
    282      * 自动条件创建时间和更新时间
    283      * @param $data
    284      * @param array $exception
    285      * @return false
    286      * @throws Exception
    287      */
    288     public function create($data, $exception = [])
    289     {
    290         try {
    291             $data['create_time'] = time();
    292             $data['update_time'] = time();
    293             $id = $this->query()->insertGetId($data);
    294 
    295             if ($id) {
    296                 $data['id'] = $id;
    297                 return $data;
    298             } else {
    299                 return false;
    300             }
    301         } catch (Exception $e) {
    302             Log::record(Db::getLastSql(), 'SQL-ERROR');
    303             Log::record($e->getMessage(), 'SQL-ERROR');
    304             if ($exception) {
    305                 throw new Exception($exception);
    306             }
    307             return false;
    308         }
    309     }
    310 
    311     /**
    312      * 根据数组和key 获取ids
    313      * @param array $arr
    314      * @param null $key
    315      * @return bool|string
    316      */
    317     public function getIds($arr = [], $key = null)
    318     {
    319         if (empty($arr) || empty($key)) {
    320             return false;
    321         }
    322         $res = [];
    323         foreach ($arr as $k => $v) {
    324             $res[] = $v[$key];
    325         }
    326         $res = implode(',', $res);
    327         return $res;
    328     }
    329 
    330 
    331     /** 更新数据信息
    332      * 自动添加更新时间
    333      * @param $where
    334      * @param $data
    335      * @param array $exception
    336      * @return false
    337      * @throws Exception
    338      */
    339     public function update($where, $data, $exception = [])
    340     {
    341         try {
    342             if (!is_array($where)) {
    343                 $where = [
    344                     'id' => $where
    345                 ];
    346             }
    347             $data['update_time'] = time();
    348             return $this->query()->where($where)->update($data);
    349         } catch (Exception $e) {
    350             Log::record(Db::getLastSql(), 'SQL-ERROR');
    351             Log::record($e->getMessage(), 'SQL-ERROR');
    352             if ($exception) {
    353                 throw new Exception($exception);
    354             }
    355             return false;
    356         }
    357     }
    358 
    359 }
  • 相关阅读:
    pinyin4j 实现 中文和拼音之间转化
    关于Exceptionless日志收集框架如何关闭磁盘缓存
    WPF桌面程序在请求接口时如何防止被常用的抓包软件Fiddler抓包
    Docker可视化容器Portainer
    记我第一次玩Docker
    最火热的极速开发框架Spring Boot
    MySQL开发规范
    5分钟入门AWK
    必须掌握的30种SQL语句优化
    支付接口的幂等性设计
  • 原文地址:https://www.cnblogs.com/hiit/p/15049059.html
Copyright © 2011-2022 走看看