SCache.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. <?php
  2. namespace App\Module\LCache;
  3. use UCore\Helper\CacheTag;
  4. use UCore\Helper\Logger;
  5. /**
  6. * symfony/cache使用laravel的配置的封装
  7. *
  8. *
  9. */
  10. class SCache
  11. {
  12. /**
  13. * 设置数据
  14. *
  15. * @param $key
  16. * @param $data
  17. * @param $exp
  18. * @param $tags
  19. * @return void
  20. */
  21. static public function put($key, $data, $exp = 60, $tags = [])
  22. {
  23. $key = self::getKey($key);
  24. if ($data instanceof CacheItem) {
  25. $d2 = $data;
  26. } else {
  27. $d2 = new CacheItem($key, $data, time(), $exp);
  28. }
  29. \Illuminate\Support\Facades\Cache::put($key, $d2, $exp);
  30. if ($tags) {
  31. CacheTag::key_tags($key, $tags, null);
  32. }
  33. return $d2;
  34. }
  35. /**
  36. * 获取数据
  37. *
  38. * @param $key
  39. * @param $default
  40. * @return CacheItem
  41. */
  42. static public function get($key, $default = null)
  43. {
  44. $key = self::getKey($key);
  45. Logger::debug("Cache-get" . $key);
  46. $res = \Illuminate\Support\Facades\Cache::get($key, $default);
  47. if ($res instanceof CacheItem) {
  48. Logger::debug("Cache-get hit" . $key);
  49. $res->isHit();
  50. return $res;
  51. }
  52. $res = new CacheItem($key, $default, 0);
  53. $res->setHit(false)->expiresAfter(-1);
  54. Logger::debug("Cache-get no hit" . $key);
  55. return $res;
  56. }
  57. /**
  58. * 获取数据
  59. * @param $key
  60. * @param $default
  61. * @return mixed|null
  62. */
  63. static public function getValue($key, $default = null)
  64. {
  65. $item = self::get($key, $default);
  66. return $item->getValue();
  67. }
  68. /**
  69. * has数据
  70. *
  71. * @param $key
  72. * @return bool
  73. */
  74. static public function has($key)
  75. {
  76. $key = self::getKey($key);
  77. return \Illuminate\Support\Facades\Cache::has($key);
  78. }
  79. static public function getTags($key)
  80. {
  81. $key = self::getKey($key);
  82. }
  83. /**
  84. * 获取键名
  85. *
  86. * @param $data
  87. * @return string
  88. */
  89. static public function getKey($data)
  90. {
  91. if(is_string($data)){
  92. return $data;
  93. }
  94. return md5(serialize($data));
  95. }
  96. }