ServiceAppAop.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. namespace App\Traits;
  3. use App\Exceptions\FatalException;
  4. use App\MaterialBox;
  5. use Illuminate\Contracts\Foundation\Application;
  6. use Illuminate\Support\Collection;
  7. use Illuminate\Support\Facades\Cache;
  8. trait ServiceAppAop
  9. {
  10. /**
  11. * 实例化一个service的入口,为了测试方便做出来的,这样测试时可以代入假的柱件替换service的实现
  12. * 应当在一般性用app的地方换成本方法才可以做到使用柱件
  13. * @param $targetService
  14. * @param $abstract
  15. * @return Application|mixed|string
  16. */
  17. public function instant(&$targetService, $abstract){
  18. if(!is_string($targetService)){
  19. if(empty($targetService))
  20. $targetService=app($abstract);
  21. return $targetService;
  22. }
  23. if(!is_string($abstract)){
  24. $this->$targetService=$abstract;
  25. }else{
  26. $this->$targetService=app($abstract);
  27. }
  28. return $targetService;
  29. }
  30. /**
  31. * 缓存过了
  32. * @param array $kvPairs
  33. * @return Collection|null
  34. */
  35. function get(array $kvPairs):?Collection{
  36. return Cache::remember($this->cachingKey($kvPairs), config('cache.expirations.serviceAutoCache'), function ()use($kvPairs) {
  37. $query = ($this->modelClass)::query();
  38. foreach ($kvPairs as $column => $value){
  39. if (is_array($value))$query->whereIn($column,$value);
  40. else $query->where($column,$value);
  41. }
  42. return $query->get();
  43. });
  44. }
  45. protected function cachingKey(array $kvPairs): string
  46. {
  47. ksort($kvPairs);
  48. return 'MaterialBox_'.md5(json_encode($kvPairs));
  49. }
  50. protected function clearCache(array $kvPairs){
  51. Cache::forget($this->cachingKey($kvPairs));
  52. }
  53. function create(array $kvPairs){
  54. $materialBox=$this->get($kvPairs);
  55. if($materialBox->isNotEmpty())
  56. return $materialBox->first();
  57. $this->clearCache($kvPairs);
  58. return ($this->modelClass)::query()->create($kvPairs);
  59. }
  60. function firstOrCreate(array $kvPairs){
  61. $materialBox=$this->get($kvPairs);
  62. if($materialBox->isNotEmpty())
  63. return $materialBox->first();
  64. $this->clearCache($kvPairs);
  65. return $this->create($kvPairs);
  66. }
  67. }