Skip to content

Commit 7069c0a

Browse files
committed
add rememberWithTags method for easier usage
1 parent 168d9fb commit 7069c0a

File tree

3 files changed

+50
-1
lines changed

3 files changed

+50
-1
lines changed

src/AlternativeRedisCacheStore.php

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
<?php
2+
3+
namespace Anorgan\LaravelCache;
4+
5+
use \AlternativeLaravelCache\Store\AlternativeRedisCacheStore as BaseAlternativeRedisCacheStore;
6+
use Illuminate\Database\Eloquent\Model;
7+
use Illuminate\Support\Collection;
8+
9+
class AlternativeRedisCacheStore extends BaseAlternativeRedisCacheStore
10+
{
11+
/**
12+
* @param $key
13+
* @param $minutes
14+
* @param Closure $callback
15+
* @param array $tags
16+
*/
17+
public function rememberWithTags($key, $minutes, \Closure $callback, array $tags = [])
18+
{
19+
// If the item exists in the cache we will just return this immediately
20+
// otherwise we will execute the given Closure and cache the result
21+
// of that execution for the given number of minutes in storage.
22+
if (! is_null($value = $this->get($key))) {
23+
return $value;
24+
}
25+
26+
$value = $callback();
27+
28+
if ($value instanceof Collection || $value instanceof Model) {
29+
$tags = array_merge(app(TagFinder::class)->find($value), $tags);
30+
}
31+
32+
$this
33+
->tags($tags)
34+
->put($key, $value, $minutes);
35+
36+
return $value;
37+
}
38+
}

src/LaravelCacheServiceProvider.php

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,17 @@ public function boot()
4343
public function register()
4444
{
4545
$this->app->register(AlternativeCacheStoresServiceProvider::class);
46+
$this->app->afterResolving('cache', function () {
47+
$cacheManager = $this->app->make('cache');
48+
$cacheManager->extend('redis', function ($app, array $cacheConfig) use ($cacheManager) {
49+
$store = new AlternativeRedisCacheStore(
50+
$app['redis'],
51+
array_get($cacheConfig, 'prefix') ?: config('cache.prefix'),
52+
array_get($cacheConfig, 'connection', 'default') ?: 'default'
53+
);
54+
return $cacheManager->repository($store);
55+
});
56+
});
4657
$this->mergeConfigFrom(__DIR__.'/../config/laravel-cache.php', 'laravel-cache');
4758
}
4859
}

src/TagFinder.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ private function getTags(Model $model)
5252
foreach ($model->getRelations() as $relation) {
5353
if ($relation instanceof Collection) {
5454
$tags = array_merge($tags, $this->getTagsFromCollection($relation));
55-
} else {
55+
} elseif ($relation instanceof Model) {
5656
$tags = array_merge($tags, $this->getTags($relation));
5757
}
5858
}

0 commit comments

Comments
 (0)