From 26074601a1ef7f09cdce26818bd9f6c0f292e591 Mon Sep 17 00:00:00 2001 From: "Jerome (Thavarshan) Thayananthajothy" Date: Wed, 10 Apr 2024 11:49:18 +0100 Subject: [PATCH] Update PostFilter constructor to accept a nullable cache handler --- README.md | 2 +- src/Filterable/Filter.php | 36 ++++++++++++++++++++++++++++++++---- 2 files changed, 33 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 23c7f46..8c57cb4 100644 --- a/README.md +++ b/README.md @@ -95,7 +95,7 @@ You can apply filters to your Eloquent queries like so: ```php use App\Models\Post; -$filter = new PostFilter(request()); +$filter = new PostFilter(request(), cache()); $posts = Post::query() ->filter($filter) ->get(); diff --git a/src/Filterable/Filter.php b/src/Filterable/Filter.php index 5df4966..3ff9e27 100644 --- a/src/Filterable/Filter.php +++ b/src/Filterable/Filter.php @@ -130,14 +130,14 @@ abstract class Filter implements FilterInterface /** * Create a new filter instance. * - * @param \Illuminate\Http\Request $request - * @param \Illuminate\Contracts\Cache\Repository $cache + * @param \Illuminate\Http\Request $request + * @param \Illuminate\Contracts\Cache\Repository|null $cache * * @return void */ public function __construct( protected Request $request, - protected Cache $cache + protected ?Cache $cache = null ) { } @@ -195,7 +195,7 @@ protected function applyFilterables(): void return; } - $this->cache->remember( + $this->getCacheHandler()->remember( $this->buildCacheKey(), Carbon::now()->addMinutes($this->getCacheExpiration()), function () { @@ -465,4 +465,32 @@ public function clearCache(): void { $this->cache->forget($this->buildCacheKey()); } + + /** + * Get the value of cache + * + * @return \Illuminate\Contracts\Cache\Repository + */ + public function getCacheHandler(): Cache + { + if (is_null($this->cache)) { + $this->cache = cache(); + } + + return $this->cache; + } + + /** + * Set the value of cache + * + * @param \Illuminate\Contracts\Cache\Repository $cache + * + * @return self + */ + public function setCacheHandler(Cache $cache) + { + $this->cache = $cache; + + return $this; + } }