forked from rinvex/laravel-cacheable
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CacheableEloquent.php
377 lines (327 loc) · 9.4 KB
/
CacheableEloquent.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
<?php
/*
* NOTICE OF LICENSE
*
* Part of the Rinvex Cacheable Package.
*
* This source file is subject to The MIT License (MIT)
* that is bundled with this package in the LICENSE file.
*
* Package: Rinvex Cacheable Package
* License: The MIT License (MIT)
* Link: https://rinvex.com
*/
declare(strict_types=1);
namespace Rinvex\Cacheable;
use Closure;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
trait CacheableEloquent
{
/**
* Indicate if the model cache clear is enabled.
*
* @var bool
*/
protected static $cacheClearEnabled = true;
/**
* The model cache driver.
*
* @var string
*/
protected $cacheDriver;
/**
* The model cache lifetime.
*
* @var float|int
*/
protected $cacheLifetime = -1;
/**
* Register an updated model event with the dispatcher.
*
* @param \Closure|string $callback
*
* @return void
*/
abstract public static function updated($callback);
/**
* Register a created model event with the dispatcher.
*
* @param \Closure|string $callback
*
* @return void
*/
abstract public static function created($callback);
/**
* Register a deleted model event with the dispatcher.
*
* @param \Closure|string $callback
*
* @return void
*/
abstract public static function deleted($callback);
/**
* Forget model cache on create/update/delete.
*
* @return void
*/
public static function bootCacheableEloquent()
{
static::attacheEvents();
}
/**
* Store the given cache key for the given model by mimicking cache tags.
*
* @param string $modelName
* @param string $cacheKey
*
* @return void
*/
protected static function storeCacheKey(string $modelName, string $cacheKey)
{
$keysFile = storage_path('framework/cache/data/rinvex.cacheable.json');
$cacheKeys = static::getCacheKeys($keysFile);
if (! isset($cacheKeys[$modelName]) || ! in_array($cacheKey, $cacheKeys[$modelName])) {
$cacheKeys[$modelName][] = $cacheKey;
file_put_contents($keysFile, json_encode($cacheKeys));
}
}
/**
* Get cache keys from the given file.
*
* @param string $file
*
* @return array
*/
protected static function getCacheKeys($file)
{
if (! file_exists($file)) {
file_put_contents($file, null);
}
return json_decode(file_get_contents($file), true) ?: [];
}
/**
* Flush cache keys of the given model by mimicking cache tags.
*
* @param string $modelName
*
* @return array
*/
protected static function flushCacheKeys(string $modelName): array
{
$flushedKeys = [];
$keysFile = storage_path('framework/cache/data/rinvex.cacheable.json');
$cacheKeys = static::getCacheKeys($keysFile);
if (isset($cacheKeys[$modelName])) {
$flushedKeys = $cacheKeys[$modelName];
unset($cacheKeys[$modelName]);
file_put_contents($keysFile, json_encode($cacheKeys));
}
return $flushedKeys;
}
/**
* Set the model cache lifetime.
*
* @param float|int $cacheLifetime
*
* @return $this
*/
public function setCacheLifetime($cacheLifetime)
{
$this->cacheLifetime = $cacheLifetime;
return $this;
}
/**
* Get the model cache lifetime.
*
* @return float|int
*/
public function getCacheLifetime()
{
return $this->cacheLifetime;
}
/**
* Set the model cache driver.
*
* @param string $cacheDriver
*
* @return $this
*/
public function setCacheDriver($cacheDriver)
{
$this->cacheDriver = $cacheDriver;
return $this;
}
/**
* Get the model cache driver.
*
* @return string
*/
public function getCacheDriver()
{
return $this->cacheDriver;
}
/**
* Determine if model cache clear is enabled.
*
* @return bool
*/
public static function isCacheClearEnabled()
{
return static::$cacheClearEnabled;
}
/**
* Forget the model cache.
*
* @return void
*/
public static function forgetCache()
{
static::fireCacheFlushEvent('cache.flushing');
// Flush cache tags
if (method_exists(app('cache')->getStore(), 'tags')) {
app('cache')->tags(static::class)->flush();
} else {
// Flush cache keys, then forget actual cache
foreach (static::flushCacheKeys(static::class) as $cacheKey) {
app('cache')->forget($cacheKey);
}
}
static::fireCacheFlushEvent('cache.flushed', false);
}
/**
* Fire the given event for the model.
*
* @param string $event
* @param bool $halt
*
* @return mixed
*/
protected static function fireCacheFlushEvent($event, $halt = true)
{
if (! isset(static::$dispatcher)) {
return true;
}
// We will append the names of the class to the event to distinguish it from
// other model events that are fired, allowing us to listen on each model
// event set individually instead of catching event for all the models.
$event = "eloquent.{$event}: ".static::class;
$method = $halt ? 'until' : 'fire';
return static::$dispatcher->$method($event, static::class);
}
/**
* Reset cached model to its defaults.
*
* @return $this
*/
public function resetCacheConfig()
{
$this->cacheDriver = null;
$this->cacheLifetime = null;
return $this;
}
/**
* Generate unique cache key.
*
* @param \Illuminate\Database\Eloquent\Builder $builder
* @param array $columns
*
* @return string
*/
protected function generateCacheKey(Builder $builder, array $columns)
{
$query = $builder->getQuery();
$vars = [
'aggregate' => $query->aggregate,
'columns' => $query->columns,
'distinct' => $query->distinct,
'from' => $query->from,
'joins' => $query->joins,
'wheres' => $query->wheres,
'groups' => $query->groups,
'havings' => $query->havings,
'orders' => $query->orders,
'limit' => $query->limit,
'offset' => $query->offset,
'unions' => $query->unions,
'unionLimit' => $query->unionLimit,
'unionOffset' => $query->unionOffset,
'unionOrders' => $query->unionOrders,
'lock' => $query->lock,
];
return md5(json_encode([
$vars,
$columns,
static::class,
$this->getCacheDriver(),
$this->getCacheLifetime(),
$builder->getEagerLoads(),
$builder->getBindings(),
$builder->toSql(),
]));
}
/**
* Cache given callback.
*
* @param \Illuminate\Database\Eloquent\Builder $builder
* @param array $columns
* @param \Closure $closure
*
* @return mixed
*/
public function cacheQuery(Builder $builder, array $columns, Closure $closure)
{
$modelName = static::class;
$lifetime = $this->getCacheLifetime();
$cacheKey = $this->generateCacheKey($builder, $columns);
// Switch cache driver on runtime
if ($driver = $this->getCacheDriver()) {
app('cache')->setDefaultDriver($driver);
}
// We need cache tags, check if default driver supports it
if (method_exists(app('cache')->getStore(), 'tags')) {
$result = $lifetime === -1 ? app('cache')->tags($modelName)->rememberForever($cacheKey, $closure) : app('cache')->tags($modelName)->remember($cacheKey, $lifetime, $closure);
return $result;
}
$result = $lifetime === -1 ? app('cache')->rememberForever($cacheKey, $closure) : app('cache')->remember($cacheKey, $lifetime, $closure);
// Default cache driver doesn't support tags, let's do it manually
static::storeCacheKey($modelName, $cacheKey);
// We're done, let's clean up!
$this->resetCacheConfig();
return $result;
}
/**
* Create a new Eloquent query builder for the model.
*
* @param \Illuminate\Database\Query\Builder $query
*
* @return \Illuminate\Database\Eloquent\Builder|static
*/
public function newEloquentBuilder($query)
{
return new EloquentBuilder($query);
}
/**
* Attach events to the model.
*
* @return void
*/
protected static function attacheEvents()
{
static::updated(function (Model $cachedModel) {
if ($cachedModel::isCacheClearEnabled()) {
$cachedModel::forgetCache();
}
});
static::created(function (Model $cachedModel) {
if ($cachedModel::isCacheClearEnabled()) {
$cachedModel::forgetCache();
}
});
static::deleted(function (Model $cachedModel) {
if ($cachedModel::isCacheClearEnabled()) {
$cachedModel::forgetCache();
}
});
}
}