Cache.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. <?php
  2. namespace UCore\Helper;
  3. use Illuminate\Support\Facades\Log;
  4. /**
  5. * 缓存助手类
  6. */
  7. class Cache
  8. {
  9. /**
  10. * 回调函数的缓存
  11. *
  12. * @param $key
  13. * @param callable $callable
  14. * @param $param_arr
  15. * @param int $exp 过期秒数
  16. * @return mixed
  17. *
  18. */
  19. static public function cacheCall($key2, callable $callable, $param_arr, $exp = 60, $tags = [])
  20. {
  21. $key = self::getKey($key2);
  22. if($exp){
  23. $old = \Illuminate\Support\Facades\Cache::get($key);
  24. if (!is_null($old)) {
  25. return $old;
  26. }
  27. }
  28. $new = call_user_func_array($callable, $param_arr);
  29. if($exp){
  30. \Illuminate\Support\Facades\Cache::put($key, $new, $exp);
  31. }
  32. if ($tags) {
  33. CacheTag::key_tags($key, $tags, null);
  34. }
  35. return $new;
  36. }
  37. /**
  38. * 设置数据
  39. *
  40. * @param $key
  41. * @param $data
  42. * @param $exp
  43. * @param $tags
  44. * @return void
  45. */
  46. static public function put($key, $data, $exp = 60, $tags = [])
  47. {
  48. $key = self::getKey($key);
  49. \Illuminate\Support\Facades\Cache::put($key, $data, $exp);
  50. if ($tags) {
  51. CacheTag::key_tags($key, $tags, null);
  52. }
  53. }
  54. /**
  55. * 获取数据
  56. *
  57. * @param $key
  58. * @param $default
  59. * @return mixed
  60. */
  61. static public function get($key, $default = null)
  62. {
  63. $key = self::getKey($key);
  64. Logger::debug("Cache-get".$key);
  65. return \Illuminate\Support\Facades\Cache::get($key,$default);
  66. }
  67. /**
  68. * has数据
  69. * @param $key
  70. * @return bool
  71. */
  72. static public function has($key)
  73. {
  74. $key = self::getKey($key);
  75. return \Illuminate\Support\Facades\Cache::has($key);
  76. }
  77. static public function getTags($key)
  78. {
  79. $key = self::getKey($key);
  80. }
  81. /**
  82. * 获取键名
  83. * @param $data
  84. * @return string
  85. */
  86. static public function getKey($data)
  87. {
  88. return md5(serialize($data));
  89. }
  90. }