Cache.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. <?php
  2. namespace app\framework\Repository\Source;
  3. use app\framework\Repository\RepositorySourceInterface;
  4. use Illuminate\Cache\CacheManager;
  5. use Illuminate\Database\Eloquent\Model;
  6. class Cache implements RepositorySourceInterface
  7. {
  8. /**
  9. * @var CacheManager
  10. */
  11. protected $cache;
  12. /**
  13. * @var mixed
  14. */
  15. protected $cacheTime;
  16. /**
  17. * @var string
  18. */
  19. private $tableName;
  20. /**
  21. * @var Model
  22. */
  23. private $model;
  24. public function __construct(Model $model, $cacheTime = null)
  25. {
  26. $this->model = $model;
  27. $this->tableName = $model->getTable();
  28. $this->cache = app('cache');
  29. $this->cacheTime = $cacheTime ?: config('cache.time', 1);
  30. }
  31. public function find($id)
  32. {
  33. return $this->cache->get("{$this->tableName}.find.{$id}");
  34. }
  35. public function findMany($ids)
  36. {
  37. $result = null;
  38. foreach ($ids as $id) {
  39. $item = $this->find($id);
  40. if ($item) {
  41. $result[] = $item;
  42. }
  43. }
  44. return $result;
  45. }
  46. public function findBy($key, $id)
  47. {
  48. return $this->cache->get("{$this->tableName}.findBy{$key}.{$id}");
  49. }
  50. public function findManyBy($key, $ids)
  51. {
  52. $result = null;
  53. foreach ($ids as $id) {
  54. $item = $this->findBy($key, $id);
  55. if ($item) {
  56. $result[] = $item;
  57. }
  58. }
  59. return $result;
  60. }
  61. public function all()
  62. {
  63. return $this->cache->get("{$this->tableName}.all");
  64. }
  65. public function save($id, $data)
  66. {
  67. return $this->cache->put("{$this->tableName}.find.{$id}", $data, $this->cacheTime);
  68. }
  69. public function saveMany($data)
  70. {
  71. foreach ($data as $item) {
  72. $this->cache->put("{$this->tableName}.find.{$item[$this->model->getKeyName()]}", $item, $this->cacheTime);
  73. }
  74. return true;
  75. }
  76. public function saveBy($key, $id, $data)
  77. {
  78. return $this->cache->put("{$this->tableName}.findBy{$key}.{$id}", $data, $this->cacheTime);
  79. }
  80. public function saveManyBy($key, $data)
  81. {
  82. foreach ($data as $item) {
  83. $this->cache->put("{$this->tableName}.findBy{$key}.{$item[$key]}", $item, $this->cacheTime);
  84. }
  85. return true;
  86. }
  87. public function saveAll($data)
  88. {
  89. $result = $this->cache->put("{$this->tableName}.all", $data->toArray(), $this->cacheTime);
  90. return $result;
  91. }
  92. public function flush()
  93. {
  94. return $this->cache->forget("{$this->tableName}.all");
  95. }
  96. }