SettingCache.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: shenyang
  5. * Date: 2018/9/14
  6. * Time: 下午5:30
  7. */
  8. namespace app\common\helpers;
  9. use app\common\facades\Setting;
  10. class SettingCache
  11. {
  12. private $settingCollection;
  13. private $expiredTimestamp;
  14. public function loadSettingFromCache($uniacid)
  15. {
  16. $this->settingCollection[$uniacid] = \Cache::get($uniacid . '_setting') ?: [];
  17. $this->expiredTimestamp[$uniacid] = time() + 20;
  18. }
  19. public function getSetting()
  20. {
  21. if (!$this->settingCollection || !in_array(Setting::$uniqueAccountId, array_keys($this->settingCollection))) {
  22. $this->loadSettingFromCache(Setting::$uniqueAccountId);
  23. }
  24. if (time() > $this->expiredTimestamp[Setting::$uniqueAccountId]) {
  25. $this->loadSettingFromCache(Setting::$uniqueAccountId);
  26. }
  27. return $this->settingCollection[Setting::$uniqueAccountId];
  28. }
  29. /**
  30. * @param $key
  31. * @return bool
  32. */
  33. public function has($key)
  34. {
  35. return array_has($this->getSetting(), $key);
  36. }
  37. /**
  38. * @param $key
  39. * @param null $default
  40. * @return mixed
  41. */
  42. public function get($key, $default = null)
  43. {
  44. return array_get($this->getSetting(), $key, $default);
  45. }
  46. public function push($key, $value, $minutes = null)
  47. {
  48. $arrayValue = $this->get($key, []);
  49. $arrayValue[] = $value;
  50. $this->put($key, $arrayValue, $minutes);
  51. }
  52. /**
  53. * @param $key
  54. * @param $value
  55. * @param null $minutes
  56. * @return mixed
  57. */
  58. public function put($key, $value, $minutes = null)
  59. {
  60. $this->loadSettingFromCache(Setting::$uniqueAccountId);
  61. $setting = $this->getSetting();
  62. $setting = yz_array_set($setting, $key, $value);
  63. \Cache::put(Setting::$uniqueAccountId . '_setting', $setting, $minutes);
  64. $this->loadSettingFromCache(Setting::$uniqueAccountId);
  65. }
  66. }