1 | <?php |
||
10 | class Cache implements CacheContract |
||
11 | { |
||
12 | /** |
||
13 | * @var RepositoryContract |
||
14 | */ |
||
15 | protected $repository; |
||
16 | |||
17 | /** |
||
18 | * @var LaravelCache |
||
19 | */ |
||
20 | protected $cache; |
||
21 | |||
22 | /** |
||
23 | * @var bool |
||
24 | */ |
||
25 | protected $skipCache = false; |
||
26 | |||
27 | /** |
||
28 | * @var bool |
||
29 | */ |
||
30 | protected $refreshCache = false; |
||
31 | |||
32 | /** |
||
33 | * @var string |
||
34 | */ |
||
35 | protected $key; |
||
36 | |||
37 | /** |
||
38 | * @var integer |
||
39 | */ |
||
40 | protected $lifetime; |
||
41 | |||
42 | /** |
||
43 | * |
||
44 | */ |
||
45 | 6 | public function __construct(RepositoryContract $repository, LaravelCache $cache) |
|
50 | |||
51 | /** |
||
52 | * |
||
53 | */ |
||
54 | 3 | public function __call($method, $params) |
|
55 | { |
||
56 | 3 | if (!method_exists($this->repository, $method)) { |
|
57 | 1 | throw new RepositoryException("Method $method not found on repository"); |
|
58 | } |
||
59 | |||
60 | 2 | if ($this->skipCache === true || config('laravel-database.cache') === false) { |
|
61 | 1 | return call_user_func_array(array($this->repository, $method), $params); |
|
62 | } else { |
||
63 | 1 | if (empty($this->key)) { |
|
64 | 1 | $this->cacheKey($this->generateKey($method, $params)); |
|
65 | 1 | } |
|
66 | 1 | $key = $this->key; |
|
67 | 1 | unset($this->key); |
|
68 | |||
69 | 1 | if ($this->refreshCache) { |
|
70 | 1 | $this->cache->forget($key); |
|
71 | |||
72 | 1 | $this->refreshCache = false; |
|
73 | 1 | } |
|
74 | |||
75 | 1 | if (empty($this->lifetime)) { |
|
76 | 1 | $this->cacheLifetime($this->repository->getModel()->cacheLifetime()); |
|
77 | 1 | } |
|
78 | 1 | $lifetime = $this->lifetime; |
|
79 | 1 | unset($this->lifetime); |
|
80 | |||
81 | 1 | return $this->cache->remember($key, $lifetime, function() use ($method, $params) { |
|
82 | return call_user_func_array(array($this->repository, $method), $params); |
||
83 | 1 | }); |
|
84 | } |
||
85 | } |
||
86 | |||
87 | /** |
||
88 | * |
||
89 | */ |
||
90 | 1 | protected function generateKey($method, $params) |
|
96 | |||
97 | /** |
||
98 | * |
||
99 | */ |
||
100 | 1 | public function skipCache($status = true) |
|
106 | |||
107 | /** |
||
108 | * |
||
109 | */ |
||
110 | 1 | public function refreshCache() |
|
116 | |||
117 | /** |
||
118 | * |
||
119 | */ |
||
120 | 1 | public function cacheKey($name) |
|
126 | |||
127 | /** |
||
128 | * |
||
129 | */ |
||
130 | 1 | public function cacheLifetime($minutes) |
|
136 | } |
||
137 |