Skip to content

Commit

Permalink
add rememberWithTags method for easier usage
Browse files Browse the repository at this point in the history
  • Loading branch information
anorgan committed Jul 25, 2017
1 parent 168d9fb commit 7069c0a
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 1 deletion.
38 changes: 38 additions & 0 deletions src/AlternativeRedisCacheStore.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php

namespace Anorgan\LaravelCache;

use \AlternativeLaravelCache\Store\AlternativeRedisCacheStore as BaseAlternativeRedisCacheStore;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;

class AlternativeRedisCacheStore extends BaseAlternativeRedisCacheStore
{
/**
* @param $key
* @param $minutes
* @param Closure $callback
* @param array $tags
*/
public function rememberWithTags($key, $minutes, \Closure $callback, array $tags = [])
{
// If the item exists in the cache we will just return this immediately
// otherwise we will execute the given Closure and cache the result
// of that execution for the given number of minutes in storage.
if (! is_null($value = $this->get($key))) {
return $value;
}

$value = $callback();

if ($value instanceof Collection || $value instanceof Model) {
$tags = array_merge(app(TagFinder::class)->find($value), $tags);
}

$this
->tags($tags)
->put($key, $value, $minutes);

return $value;
}
}
11 changes: 11 additions & 0 deletions src/LaravelCacheServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,17 @@ public function boot()
public function register()
{
$this->app->register(AlternativeCacheStoresServiceProvider::class);
$this->app->afterResolving('cache', function () {
$cacheManager = $this->app->make('cache');
$cacheManager->extend('redis', function ($app, array $cacheConfig) use ($cacheManager) {
$store = new AlternativeRedisCacheStore(
$app['redis'],
array_get($cacheConfig, 'prefix') ?: config('cache.prefix'),
array_get($cacheConfig, 'connection', 'default') ?: 'default'
);
return $cacheManager->repository($store);
});
});
$this->mergeConfigFrom(__DIR__.'/../config/laravel-cache.php', 'laravel-cache');
}
}
2 changes: 1 addition & 1 deletion src/TagFinder.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ private function getTags(Model $model)
foreach ($model->getRelations() as $relation) {
if ($relation instanceof Collection) {
$tags = array_merge($tags, $this->getTagsFromCollection($relation));
} else {
} elseif ($relation instanceof Model) {
$tags = array_merge($tags, $this->getTags($relation));
}
}
Expand Down

0 comments on commit 7069c0a

Please sign in to comment.