Skip to content

Commit

Permalink
Get cache tags once when invalidating
Browse files Browse the repository at this point in the history
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;
}
```
  • Loading branch information
squatto authored Jan 21, 2022
1 parent 7e77875 commit 7bd849c
Showing 1 changed file with 4 additions and 4 deletions.
8 changes: 4 additions & 4 deletions src/FlushQueryCacheObserver.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}

0 comments on commit 7bd849c

Please sign in to comment.