Cache::once()
— auto-keyed caching based on callsite
#56499
Unanswered
plumthedev
asked this question in
Ideas
Replies: 2 comments 6 replies
-
We already have a memo feature. Does this modify the existing code, or did you simply miss it? https://laravel.com/docs/12.x/cache#cache-memoization |
Beta Was this translation helpful? Give feedback.
6 replies
-
@nunomaduro @taylorotwell @crynobone @driesvints if you have a moment, would love your thoughts on this approach 😃 |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
🎯 Motivation
In day-to-day Laravel development, caching frequently-used results is a common performance optimization. However, it almost always requires manually defining a cache key:
This approach leads to:
But what if the key could be automatically generated based on where the cache was invoked?
💡 Insight: The callsite is the key
We can use
debug_backtrace()
to capture the context of the callsite:This forms a unique and predictable identity for the cached computation.
✅ API Proposal
Where:
$ttl
: any value accepted byremember()
,$callback
: the actual computation to be cached,$args
: optional; used to vary the key if input differs.🧠 Example usage
No need to build or worry about keys — the system generates them deterministically based on:
once()
was called,$args
.🛠 Internals
Internally,
once()
would:debug_backtrace()
to extract class/method context,$args
,md5(json_encode(...))
),Cache::remember($key, $ttl, $callback)
under the hood.Argument processing (for stable keys):
$model->getKey()
,Request
, serialize its inputs,__toString()
, use the string,json_encode()
of primitives/arrays.🔄 Optional Extensions
KeyGeneratorInterface
for custom strategies.⚙️ Benefits
✅ Zero boilerplate – no key-building
✅ Predictable, context-based identity
✅ Clean, Laravel-style API
✅ Easier to generalize across codebases
✅ Fully extendable/customizable under the hood
🧪 Summary
Cache::once()
introduces a cleaner, safer, and more elegant way to handle caching in Laravel. It leverages Laravel's expressive syntax and conventions while abstracting key management.I'd be happy to open a PR implementing this as a native method in the CacheManager — not just a macro. I believe it fits Laravel’s philosophy and would improve developer experience significantly.
Beta Was this translation helpful? Give feedback.
All reactions