Skip to content

Commit 37c268a

Browse files
committed
Add initial model
1 parent 71e66e0 commit 37c268a

File tree

2 files changed

+78
-0
lines changed

2 files changed

+78
-0
lines changed

composer.json

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
{
2+
"name": "genealabs/laravel-cached-model",
3+
"description": "Automatic caching for Eloquent models.",
4+
"license": "MIT",
5+
"authors": [
6+
{
7+
"name": "Mike Bronner",
8+
"email": "[email protected]"
9+
}
10+
],
11+
"require": {
12+
"php": ">=7.0.0",
13+
"illuminate/cache": "5.5.*",
14+
"illuminate/database": "5.5.*"
15+
},
16+
"require-dev": {
17+
"laravel/laravel": "5.5.*",
18+
"mockery/mockery": "0.9.*",
19+
"phpmd/phpmd": "^2.6",
20+
"phpunit/phpunit": "5.7.*",
21+
"satooshi/php-coveralls" : "dev-master@dev",
22+
"sebastian/phpcpd": "*"
23+
},
24+
"autoload": {
25+
"psr-4": {
26+
"GeneaLabs\\LaravelCachedModel\\": "src/",
27+
"GeneaLabs\\LaravelCachedModel\\Tests\\": "tests/"
28+
}
29+
}
30+
}

src/CachedModel.php

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
<?php namespace GeneaLabs\LaravelCachableModel\Traits;
2+
3+
use Illuminate\Database\Eloquent\Model;
4+
use Illuminate\Cache\CacheManager;
5+
use Illuminate\Cache\TaggableStore;
6+
7+
abstract class CachedModel extends Model
8+
{
9+
public static function boot()
10+
{
11+
parent::boot();
12+
13+
static::created(function () {
14+
self::flushCache();
15+
});
16+
17+
static::deleted(function () {
18+
self::flushCache();
19+
});
20+
21+
static::saved(function () {
22+
self::flushCache();
23+
});
24+
25+
static::updated(function () {
26+
self::flushCache();
27+
});
28+
}
29+
30+
public function cache(array $tags = [])
31+
{
32+
$cache = cache();
33+
34+
if (is_subclass_of(cache()->getStore(), TaggableStore::class)) {
35+
array_push($tags, str_slug(get_called_class()));
36+
$cache = $cache->tags($tags);
37+
}
38+
39+
return $cache;
40+
}
41+
42+
public static function flushCache()
43+
{
44+
cache()->tags([str_slug(get_called_class())])
45+
->flush();
46+
}
47+
}
48+
}

0 commit comments

Comments
 (0)