Skip to content

Commit 41f14c6

Browse files
committed
WIP - cache relationships
1 parent 37c268a commit 41f14c6

File tree

3 files changed

+60
-3
lines changed

3 files changed

+60
-3
lines changed

README.md

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,9 @@
1-
# Laravel-cached-models
1+
# Laravel-cached-models
2+
3+
## Features
4+
- automatic relationship caching.
5+
- automatic cache flushing when models are change.
6+
- automatic use of cache flags for cache providers that support them (will flush
7+
entire cache for providers that don't).
8+
- provides simple caching methods for use in query methods for models that take
9+
advantage of the automatic cache management features mentioned.

src/Builder.php

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
<?php namespace GeneaLabs\LaravelCachableModel\Traits;
2+
3+
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
4+
5+
class Builder extends EloquentBuilder
6+
{
7+
protected function eagerLoadRelation(array $models, $name, Closure $constraints)
8+
{
9+
$relation = $this->getRelation($name);
10+
$relation->addEagerConstraints($models);
11+
$constraints($relation);
12+
13+
$parentName = str_slug(get_class($relation->getParent()));
14+
$childName = str_slug(get_class($relation->getModel()));
15+
$results = cache()->tags([$parentName, $childName])
16+
->rememberForever("{$parentName}-{$childName}-relation", function () use ($relation) {
17+
return $relation->getEager();
18+
});
19+
20+
return $relation->match(
21+
$relation->initRelation($models, $name),
22+
$results,
23+
$name
24+
);
25+
}
26+
}

src/CachedModel.php

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,35 @@
11
<?php namespace GeneaLabs\LaravelCachableModel\Traits;
22

3-
use Illuminate\Database\Eloquent\Model;
3+
use Closure;
44
use Illuminate\Cache\CacheManager;
55
use Illuminate\Cache\TaggableStore;
6+
use Illuminate\Database\Eloquent\Model;
67

78
abstract class CachedModel extends Model
89
{
10+
protected function getRelationshipFromMethod($method)
11+
{
12+
$relation = $this->$method();
13+
14+
if (! $relation instanceof Relation) {
15+
throw new LogicException(get_class($this).'::'.$method.' must return a relationship instance.');
16+
}
17+
18+
$results = $this->cache([$method])
19+
->rememberForever(str_slug(get_called_class()) . "-{$method}", function () use ($relation) {
20+
return $relation->getResults();
21+
});
22+
23+
return tap($results, function ($results) use ($method) {
24+
$this->setRelation($method, $results);
25+
});
26+
}
27+
28+
public function newEloquentBuilder($query)
29+
{
30+
return new Builder($query);
31+
}
32+
933
public static function boot()
1034
{
1135
parent::boot();
@@ -45,4 +69,3 @@ public static function flushCache()
4569
->flush();
4670
}
4771
}
48-
}

0 commit comments

Comments
 (0)