1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace App\Traits; |
4
|
|
|
|
5
|
|
|
use Illuminate\Support\Facades\Input; |
6
|
|
|
use Illuminate\Support\Facades\Cache; |
7
|
|
|
|
8
|
|
|
trait CacheProtectFunction |
9
|
|
|
{ |
10
|
|
|
/** |
11
|
|
|
* @param $method |
12
|
|
|
* @param $parameters |
13
|
|
|
* @return mixed |
14
|
|
|
* cache through __call |
15
|
|
|
*/ |
16
|
|
|
public function __call($method, $parameters) |
17
|
|
|
{ |
18
|
|
|
$cacheName = __CLASS__ . ":" . $method . "_" . md5(json_encode($parameters)); |
19
|
|
|
|
20
|
|
|
$expire = $this->getExpire($method); |
21
|
|
|
|
22
|
|
|
$closure = function () use ($method, $parameters) { |
23
|
|
|
return call_user_func_array([$this, $method], $parameters); |
24
|
|
|
}; |
25
|
|
|
|
26
|
|
|
if (config('app.debug') && Input::get('skipCache')) { |
27
|
|
|
return $closure(); |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
if (config('app.debug') && Input::get('forgetCache')) { |
31
|
|
|
Cache::forget($cacheName); |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
$result = Cache::remember($cacheName, $expire, $closure); |
35
|
|
|
|
36
|
|
|
return $result; |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* @param $method |
41
|
|
|
* @return int |
42
|
|
|
* get expire by reflection |
43
|
|
|
*/ |
44
|
|
|
private function getExpire($method) |
45
|
|
|
{ |
46
|
|
|
$rf = new \ReflectionMethod($this,$method); |
47
|
|
|
$staticVar = $rf->getStaticVariables(); |
48
|
|
|
if (array_key_exists('expire',$staticVar)){ |
49
|
|
|
$expire = $staticVar['expire']; |
50
|
|
|
} else { |
51
|
|
|
$expire = 60; |
52
|
|
|
} |
53
|
|
|
return $expire; |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* @return bool |
58
|
|
|
* delete all cache from the class |
59
|
|
|
* TODO support other driver |
60
|
|
|
*/ |
61
|
|
|
public function forgetCache(){ |
62
|
|
|
$cacheName = __CLASS__ . ':*'; |
63
|
|
|
|
64
|
|
|
$redis = Cache::getRedis(); |
65
|
|
|
$keys = $redis->keys($cacheName); |
66
|
|
|
if ($keys) { |
67
|
|
|
$redis->del($keys); |
68
|
|
|
}; |
69
|
|
|
|
70
|
|
|
return true; |
71
|
|
|
} |
72
|
|
|
} |