MaterialBoxService.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. <?php
  2. namespace App\Services;
  3. use App\MaterialBox;
  4. use Illuminate\Support\Collection;
  5. use Illuminate\Support\Facades\Cache;
  6. use App\Traits\ServiceAppAop;
  7. class MaterialBoxService
  8. {
  9. use ServiceAppAop;
  10. function get(array $kvPairs):?Collection{
  11. return Cache::remember($this->cachingKey($kvPairs), config('cache.expirations.rarelyChange'), function ()use($kvPairs) {
  12. $query = MaterialBox::query();
  13. foreach ($kvPairs as $column => $value){
  14. if (is_array($value))$query->whereIn($column,$value);
  15. else $query->where($column,$value);
  16. }
  17. return $query->get();
  18. });
  19. }
  20. protected function cachingKey(array $kvPairs){
  21. ksort($kvPairs);
  22. return 'MaterialBox_'.md5(json_encode($kvPairs));
  23. }
  24. protected function clearCache(array $kvPairs){
  25. Cache::forget($this->cachingKey($kvPairs));
  26. }
  27. function create(array $kvPairs){
  28. $materialBox=$this->get($kvPairs);
  29. if($materialBox->isNotEmpty())
  30. return $materialBox->first();
  31. $this->clearCache($kvPairs);
  32. return MaterialBox::query()->create($kvPairs);
  33. }
  34. function firstOrCreate(array $kvPairs){
  35. $materialBox=$this->get($kvPairs);
  36. if($materialBox->isNotEmpty())
  37. return $materialBox->first();
  38. $this->clearCache($kvPairs);
  39. return $this->create($kvPairs);
  40. }
  41. }