|
1
|
|
|
<?php namespace GeneaLabs\LaravelModelCaching\Traits; |
|
2
|
|
|
|
|
3
|
|
|
use GeneaLabs\LaravelModelCaching\CachedBuilder; |
|
4
|
|
|
use Illuminate\Database\Eloquent\Builder as EloquentBuilder; |
|
5
|
|
|
|
|
6
|
|
|
trait ModelCaching |
|
7
|
|
|
{ |
|
8
|
|
|
public static function all($columns = ['*']) |
|
9
|
|
|
{ |
|
10
|
|
|
if (config('laravel-model-caching.disabled')) { |
|
11
|
|
|
return parent::all($columns); |
|
12
|
|
|
} |
|
13
|
|
|
|
|
14
|
|
|
$class = get_called_class(); |
|
15
|
|
|
$instance = new $class; |
|
16
|
|
|
$tags = [str_slug(get_called_class())]; |
|
17
|
|
|
$key = $instance->makeCacheKey(); |
|
18
|
|
|
|
|
19
|
|
|
return $instance->cache($tags) |
|
20
|
|
|
->rememberForever($key, function () use ($columns) { |
|
21
|
|
|
return parent::all($columns); |
|
22
|
|
|
}); |
|
23
|
|
|
} |
|
24
|
|
|
|
|
25
|
|
|
public static function bootCachable() |
|
26
|
|
|
{ |
|
27
|
|
|
static::saved(function ($instance) { |
|
28
|
|
|
$instance->checkCooldownAndFlushAfterPersiting($instance); |
|
29
|
|
|
}); |
|
30
|
|
|
|
|
31
|
|
|
static::pivotAttached(function ($instance) { |
|
32
|
|
|
$instance->checkCooldownAndFlushAfterPersiting($instance); |
|
33
|
|
|
}); |
|
34
|
|
|
|
|
35
|
|
|
static::pivotDetached(function ($instance) { |
|
36
|
|
|
$instance->checkCooldownAndFlushAfterPersiting($instance); |
|
37
|
|
|
}); |
|
38
|
|
|
|
|
39
|
|
|
static::pivotUpdated(function ($instance) { |
|
40
|
|
|
$instance->checkCooldownAndFlushAfterPersiting($instance); |
|
41
|
|
|
}); |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
public function newEloquentBuilder($query) |
|
45
|
|
|
{ |
|
46
|
|
|
if (! $this->isCachable()) { |
|
|
|
|
|
|
47
|
|
|
$this->isCachable = true; |
|
|
|
|
|
|
48
|
|
|
|
|
49
|
|
|
return new EloquentBuilder($query); |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
return new CachedBuilder($query); |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
public function scopeWithCacheCooldownSeconds( |
|
56
|
|
|
EloquentBuilder $query, |
|
57
|
|
|
int $seconds |
|
58
|
|
|
) : EloquentBuilder { |
|
59
|
|
|
$cachePrefix = $this->getCachePrefix(); |
|
|
|
|
|
|
60
|
|
|
$modelClassName = get_class($this); |
|
61
|
|
|
$cacheKey = "{$cachePrefix}:{$modelClassName}-cooldown:seconds"; |
|
62
|
|
|
|
|
63
|
|
|
$this->cache() |
|
|
|
|
|
|
64
|
|
|
->rememberForever($cacheKey, function () use ($seconds) { |
|
65
|
|
|
return $seconds; |
|
66
|
|
|
}); |
|
67
|
|
|
|
|
68
|
|
|
$cacheKey = "{$cachePrefix}:{$modelClassName}-cooldown:invalidated-at"; |
|
69
|
|
|
$this->cache() |
|
70
|
|
|
->rememberForever($cacheKey, function () { |
|
71
|
|
|
return now(); |
|
72
|
|
|
}); |
|
73
|
|
|
|
|
74
|
|
|
return $query; |
|
75
|
|
|
} |
|
76
|
|
|
} |
|
77
|
|
|
|