File tree Expand file tree Collapse file tree 3 files changed +60
-3
lines changed Expand file tree Collapse file tree 3 files changed +60
-3
lines changed Original file line number Diff line number Diff line change 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.
Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change 11<?php namespace GeneaLabs \LaravelCachableModel \Traits ;
22
3- use Illuminate \ Database \ Eloquent \ Model ;
3+ use Closure ;
44use Illuminate \Cache \CacheManager ;
55use Illuminate \Cache \TaggableStore ;
6+ use Illuminate \Database \Eloquent \Model ;
67
78abstract 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- }
You can’t perform that action at this time.
0 commit comments