MaterialBoxService.php 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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 getModelClass(): string
  11. {
  12. return MaterialBox::class;
  13. }
  14. function get(array $kvPairs):?Collection{
  15. return Cache::remember($this->cachingKey($kvPairs), config('cache.expirations.rarelyChange'), function ()use($kvPairs) {
  16. $query = MaterialBox::query();
  17. foreach ($kvPairs as $column => $value){
  18. if (is_array($value))$query->whereIn($column,$value);
  19. else $query->where($column,$value);
  20. }
  21. return $query->get();
  22. });
  23. }
  24. protected function cachingKey(array $kvPairs){
  25. ksort($kvPairs);
  26. return 'MaterialBox_'.md5(json_encode($kvPairs));
  27. }
  28. protected function clearCache(array $kvPairs){
  29. Cache::forget($this->cachingKey($kvPairs));
  30. }
  31. function create(array $kvPairs){
  32. $materialBox=$this->get($kvPairs);
  33. if($materialBox->isNotEmpty())
  34. return $materialBox->first();
  35. $this->clearCache($kvPairs);
  36. return MaterialBox::query()->create($kvPairs);
  37. }
  38. function firstOrCreate(array $kvPairs){
  39. $materialBox=$this->get($kvPairs);
  40. if($materialBox->isNotEmpty())
  41. return $materialBox->first();
  42. $this->clearCache($kvPairs);
  43. return $this->create($kvPairs);
  44. }
  45. }