| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586 |
- <?php
- namespace App\Traits;
- use App\Exceptions\FatalException;
- use App\MaterialBox;
- use Illuminate\Contracts\Foundation\Application;
- use Illuminate\Support\Collection;
- use Illuminate\Support\Facades\Cache;
- trait ServiceAppAop
- {
- protected $modelClass=null;
- /**
- * 实例化一个service的入口,为了测试方便做出来的,这样测试时可以代入假的柱件替换service的实现
- * 应当在一般性用app的地方换成本方法才可以做到使用柱件
- * @param $targetService
- * @param $abstract
- * @return Application|mixed|string
- */
- public function instant(&$targetService, $abstract){
- if(!is_string($targetService)){
- if(empty($targetService))
- $targetService=app($abstract);
- return $targetService;
- }
- if(!is_string($abstract)){
- $this->$targetService=$abstract;
- }else{
- $this->$targetService=app($abstract);
- }
- return $targetService;
- }
- /**
- * 缓存过了
- * @param array $kvPairs
- * @return Collection|null
- */
- function get(array $kvPairs):?Collection{
- return Cache::remember($this->cachingKey($kvPairs), config('cache.expirations.serviceAutoCache'), function ()use($kvPairs) {
- $query = $this->getModelClass()::query();
- foreach ($kvPairs as $column => $value){
- if (is_array($value))$query->whereIn($column,$value);
- else $query->where($column,$value);
- }
- return $query->get();
- });
- }
- protected function getModelClass(){
- if(!$this->modelClass){
- throw new FatalException(__CLASS__.': 没有为 service 设定 $modelClass 的模型类');
- }
- return $this->modelClass;
- }
- protected function cachingKey(array $kvPairs): string
- {
- ksort($kvPairs);
- return 'MaterialBox_'.md5(json_encode($kvPairs));
- }
- protected function clearCache(array $kvPairs){
- Cache::forget($this->cachingKey($kvPairs));
- }
- function create(array $kvPairs){
- $materialBox=$this->get($kvPairs);
- if($materialBox->isNotEmpty())
- return $materialBox->first();
- $this->clearCache($kvPairs);
- return $this->getModelClass()::query()->create($kvPairs);
- }
- function firstOrCreate(array $kvPairs){
- $materialBox=$this->get($kvPairs);
- if($materialBox->isNotEmpty())
- return $materialBox->first();
- $this->clearCache($kvPairs);
- return $this->create($kvPairs);
- }
- }
|