I'm building a REST API with Lumen and want to cache some of the routes with Redis. E.g. for the route /users/123/items I use:
$items = Cache::remember('users:123:items', 60, function () {
// Get data from database and return
});
When a change is made to the user's items, I clear the cache with:
Cache::forget('users:123:items');
So far so good. However, I also need to clear the cache I've implemented for the routes /users/123 and /users/123/categories since those include an item list as well. This means I also have to run:
Cache::forget('users:123');
Cache::forget('users:123:categories');
In the future, there might be even more caches to clear, which is is why I'm looking for a pattern/wildcard feature such as:
Cache::forget('users:123*');
Is there any way to accommodate this behavior in Lumen/Laravel?
You can use cache tags.
Cache tags allow you to tag related items in the cache and then flush all cached values that have been assigned a given tag. You may access a tagged cache by passing in an ordered array of tag names. For example, let's access a tagged cache and put value in the cache:
Cache::tags(['people', 'artists'])->put('John', $john, $minutes);
You may flush all items that are assigned a tag or list of tags. For example, this statement would remove all caches tagged with either people, authors, or both. So, both Anne and John would be removed from the cache:
Cache::tags(['people', 'authors'])->flush();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With