RedisBaseModel.php 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. <?php
  2. namespace app\common\model;
  3. use think\Model;
  4. use app\common\Redis;
  5. use think\facade\Config;
  6. /**
  7. * Description of RedisBaseModel
  8. *
  9. * @author sgq
  10. */
  11. class RedisBaseModel extends Model {
  12. protected static function onAfterWrite(Model $model): void {
  13. $data = $model->toArray();
  14. if ($data["id"]) {
  15. $redis = Redis::instance(Config::get("cache.stores.redis.select"));
  16. $redis->hSet($model->name, $data["id"], json_encode($data));
  17. }
  18. }
  19. protected static function onAfterDelete(Model $model): void {
  20. $data = $model->toArray();
  21. if ($data["id"]) {
  22. $redis = Redis::instance(Config::get("cache.stores.redis.select"));
  23. $redis->hDel($model->name, $data["id"]);
  24. }
  25. }
  26. public static function cache($id = 0) {
  27. $redis = Redis::instance(Config::get("cache.stores.redis.select"));
  28. if ($id) {
  29. $data = self::select($id);
  30. $name = $data->name;
  31. $redis->hSet($name, $id, json_encode($data));
  32. } else {
  33. $list = self::select();
  34. $name = $list[0]->name;
  35. $redis->del($name);
  36. foreach ($list as $data) {
  37. $redis->hSet($name, $data["id"], json_encode($data));
  38. }
  39. }
  40. }
  41. }