Completed
Pull Request — master (#18)
by Mike
03:29
created

CachedModel::newEloquentBuilder()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
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