ServiceAppAop.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. protected $modelClass=null;
  11. /**
  12. * 实例化一个service的入口,为了测试方便做出来的,这样测试时可以代入假的柱件替换service的实现
  13. * 应当在一般性用app的地方换成本方法才可以做到使用柱件
  14. * @param $targetService
  15. * @param $abstract
  16. * @return Application|mixed|string
  17. */
  18. public function instant(&$targetService, $abstract){
  19. if(!is_string($targetService)){
  20. if(empty($targetService))
  21. $targetService=app($abstract);
  22. return $targetService;
  23. }
  24. if(!is_string($abstract)){
  25. $this->$targetService=$abstract;
  26. }else{
  27. $this->$targetService=app($abstract);
  28. }
  29. return $targetService;
  30. }
  31. /**
  32. * 缓存过了
  33. * @param array $kvPairs
  34. * @return Collection|null
  35. */
  36. function get(array $kvPairs):?Collection{
  37. return Cache::remember($this->cachingKey($kvPairs), config('cache.expirations.serviceAutoCache'), function ()use($kvPairs) {
  38. $query = $this->getModelClass()::query();
  39. foreach ($kvPairs as $column => $value){
  40. if (is_array($value))$query->whereIn($column,$value);
  41. else $query->where($column,$value);
  42. }
  43. return $query->get();
  44. });
  45. }
  46. protected function getModelClass(){
  47. if(!$this->modelClass){
  48. throw new FatalException(__CLASS__.': 没有为 service 设定 $modelClass 的模型类');
  49. }
  50. return $this->modelClass;
  51. }
  52. protected function cachingKey(array $kvPairs): string
  53. {
  54. ksort($kvPairs);
  55. return 'MaterialBox_'.md5(json_encode($kvPairs));
  56. }
  57. protected function clearCache(array $kvPairs){
  58. Cache::forget($this->cachingKey($kvPairs));
  59. }
  60. function create(array $kvPairs){
  61. $materialBox=$this->get($kvPairs);
  62. if($materialBox->isNotEmpty())
  63. return $materialBox->first();
  64. $this->clearCache($kvPairs);
  65. return $this->getModelClass()::query()->create($kvPairs);
  66. }
  67. function firstOrCreate(array $kvPairs){
  68. $materialBox=$this->get($kvPairs);
  69. if($materialBox->isNotEmpty())
  70. return $materialBox->first();
  71. $this->clearCache($kvPairs);
  72. return $this->create($kvPairs);
  73. }
  74. }