1
|
|
|
<?php namespace GeneaLabs\LaravelModelCaching; |
2
|
|
|
|
3
|
|
|
use GeneaLabs\LaravelModelCaching\CachedBuilder as Builder; |
4
|
|
|
use Illuminate\Cache\CacheManager; |
5
|
|
|
use Illuminate\Cache\TaggableStore; |
6
|
|
|
use Illuminate\Database\Eloquent\Model; |
7
|
|
|
use Illuminate\Database\Eloquent\Relations\Relation; |
8
|
|
|
use LogicException; |
9
|
|
|
|
10
|
|
|
use Illuminate\Cache\TaggedCache; |
11
|
|
|
use Illuminate\Support\Collection; |
12
|
|
|
|
13
|
|
|
abstract class CachedModel extends Model |
14
|
|
|
{ |
15
|
|
|
public function newEloquentBuilder($query) |
16
|
|
|
{ |
17
|
|
|
return new Builder($query); |
18
|
|
|
} |
19
|
|
|
|
20
|
|
|
public static function boot() |
21
|
|
|
{ |
22
|
|
|
parent::boot(); |
23
|
|
|
$class = get_called_class(); |
24
|
|
|
$instance = new $class; |
25
|
|
|
|
26
|
|
|
static::created(function () use ($instance) { |
27
|
|
|
$instance->flushCache(); |
28
|
|
|
}); |
29
|
|
|
|
30
|
|
|
static::deleted(function () use ($instance) { |
31
|
|
|
$instance->flushCache(); |
32
|
|
|
}); |
33
|
|
|
|
34
|
|
|
static::saved(function () use ($instance) { |
35
|
|
|
$instance->flushCache(); |
36
|
|
|
}); |
37
|
|
|
|
38
|
|
|
static::updated(function () use ($instance) { |
39
|
|
|
$instance->flushCache(); |
40
|
|
|
}); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
public function cache(array $tags = []) |
44
|
|
|
{ |
45
|
|
|
$cache = cache(); |
46
|
|
|
|
47
|
|
|
if (is_subclass_of($cache->getStore(), TaggableStore::class)) { |
48
|
|
|
array_push($tags, str_slug(get_called_class())); |
49
|
|
|
$cache = $cache->tags($tags); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
return $cache; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
public function flushCache(array $tags = []) |
56
|
|
|
{ |
57
|
|
|
$this->cache($tags)->flush(); |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
public static function all($columns = ['*']) |
61
|
|
|
{ |
62
|
|
|
$class = get_called_class(); |
63
|
|
|
$instance = new $class; |
64
|
|
|
$tags = [str_slug(get_called_class())]; |
65
|
|
|
$key = 'genealabslaravelmodelcachingtestsfixturesauthor'; |
66
|
|
|
|
67
|
|
|
return $instance->cache($tags) |
68
|
|
|
->rememberForever($key, function () use ($columns) { |
69
|
|
|
return parent::all($columns); |
70
|
|
|
}); |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|