From 7bd849ca9c181fa51205ec8fa66f8e6931f08b10 Mon Sep 17 00:00:00 2001 From: Scott Carpenter Date: Fri, 21 Jan 2022 12:10:34 -0700 Subject: [PATCH] Get cache tags once when invalidating I'm using an overridden `getCacheTagsToInvalidateOnUpdate()` to track how many times each tag is invalidated. The way `invalidateCache()` was originally written calls the `getCacheTagsToInvalidateOnUpdate()` method twice, resulting in the tags being counted twice for each invalidation. This change simply assigns the tags to a variable and uses the variable instead of calling the method directly. FWIW, this is what I'm doing to track the tag invalidations. Just a simple array saved to the cache. ```php public function getCacheTagsToInvalidateOnUpdate($relation = null, $pivotedModels = null): array { $tags = $this->getCacheBaseTags(); $invalidations = Cache::get('cache-invalidations', []); foreach ($tags as $tag) { $invalidations[$tag] = ($invalidations[$tag] ?? 0) + 1; } Cache::forever('cache-invalidations', $invalidations); return $tags; } ``` --- src/FlushQueryCacheObserver.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/FlushQueryCacheObserver.php b/src/FlushQueryCacheObserver.php index ba049ff..7ca7ce2 100644 --- a/src/FlushQueryCacheObserver.php +++ b/src/FlushQueryCacheObserver.php @@ -154,12 +154,12 @@ protected function invalidateCache(Model $model, $relation = null, $pivotedModel { $class = get_class($model); - if (! $model->getCacheTagsToInvalidateOnUpdate($relation, $pivotedModels)) { + $tags = $model->getCacheTagsToInvalidateOnUpdate($relation, $pivotedModels); + + if (! $tags) { throw new Exception('Automatic invalidation for '.$class.' works only if at least one tag to be invalidated is specified.'); } - $class::flushQueryCache( - $model->getCacheTagsToInvalidateOnUpdate($relation, $pivotedModels) - ); + $class::flushQueryCache($tags); } }