Cache: conditionally "remember" and "rememberForever" #51594
Replies: 5 comments 6 replies
-
In my opinion this is the best option because calling the remember implies all its parameters to be processed, so if the key is a concatenation or the ttl is calculation then those will not be executed. |
Beta Was this translation helpful? Give feedback.
-
It would be useful if Cache would implement the Conditionally trait. Then you could do |
Beta Was this translation helpful? Give feedback.
-
I have needed this a couple times and had always intended to PR something in, so I'd be for it. The |
Beta Was this translation helpful? Give feedback.
-
I have a similar need to this, but want to propose an alternative solution. My idea is to add two new methods to the cache facade: /** Executes callback and returns its value, ignoring any cached values */
Cache::withoutCache(Closure $callback);
/** Executes callback and returns its value, revalidating any cached values matching keys */
Cache::forceRevalidate(Closure $callback);
// Basic Examples
Cache::put('my-cache-key', 'some-other-value');
function getSomeCachedValue() {
return Cache::remember('my-cache-key', function () {
return 'some-value';
});
}
// Returns 'some-value' without reading or writing to cache - 'my-cache-key' retains 'some-other-value'
Cache::withoutCache(function () {
return getSomeCachedValue();
});
// Returns 'some-value' and result is stored in 'my-cache-key'
Cache::forceRevalidate(function () {
return getSomeCachedValue();
}); I believe this is a more generic solution to the problem, so should have a greater variety of use cases. My own use case is that I have a lot of functions which One thing I'm unsure of in this proposal would be whether and how to support filtering the behavior (e.g. by store, tag, key, etc) if you wanted to only revalidate certain values while still using the cache for others inside the closure. I'm also unsure how methods like |
Beta Was this translation helpful? Give feedback.
-
I submitted a PR for this that was rejected: #52702 |
Beta Was this translation helpful? Give feedback.
-
Sometimes I need to cache a value depending on the current situation. For example, a value should be cached for regular users but not for admins.
At the moment, the way to achieve this is by having a condition before calling the cache:
In my opinion, it would be nice to have something like this, where the condition can be passed as the first parameter.
Another approach would be a fourth optional parameter on the existing
remember
method for thewhen
condition.The same would apply to
rememberForever()
.What do you think?
If I am not the only one, having this need, I am happy to PR the feature.
There was a similar discussion before, but it went off-track, so I decided to create a new one. See: #48890
Beta Was this translation helpful? Give feedback.
All reactions