Skip to content

Commit

Permalink
Smart page view caching
Browse files Browse the repository at this point in the history
  • Loading branch information
caendesilva committed Nov 30, 2024
1 parent 22136fe commit 0511795
Showing 1 changed file with 23 additions and 5 deletions.
28 changes: 23 additions & 5 deletions app/Models/Post.php
Original file line number Diff line number Diff line change
Expand Up @@ -151,10 +151,28 @@ public function getViewCount(): int
throw new \BadMethodCallException('Analytics are not enabled');
}

return cache()->remember(
"post.{$this->id}.views",
now()->addMinutes(config('analytics.view_count_cache_duration')),
fn() => PageView::where('page', route('posts.show', $this, false))->count()
);
$cacheKey = "post.{$this->id}.views";
$cacheDuration = config('analytics.view_count_cache_duration');

// Get the cached value (even if expired)
$value = cache()->get($cacheKey);

if ($value !== null) {
// If the cache exists but is stale, dispatch background refresh
if (! cache()->has($cacheKey)) {
dispatch(function () use ($cacheKey, $cacheDuration) {
$newValue = PageView::where('page', route('posts.show', $this, false))->count();
cache()->put($cacheKey, $newValue, now()->addMinutes($cacheDuration));
})->afterResponse();
}

return $value;
}

// If no cached value exists at all, fetch and cache synchronously
$value = PageView::where('page', route('posts.show', $this, false))->count();
cache()->put($cacheKey, $value, now()->addMinutes($cacheDuration));

return $value;
}
}

0 comments on commit 0511795

Please sign in to comment.