So I'm looking for a clean alternative that can be easily implemented.
I have some API that have various parameters, like date filters, types, and so on. I want to cache for 1 hour all the different requests with different params. So I thought about hashing the URL and use it as a key for the cache, like in the example below.
Is this a good idea? Are there better way of doing it?
$url = $request->fullUrl();
$hash = hash('sha256', $url);
$value = Cache::get($hash, function () {
// Not cached, so get data and store it in cache with $hash
$data = ...
Cache::put($hash, $data, $hours = 1);
return $data;
});
@swagger It depends how often the results from the API change. There’s no point caching the request (and response) if the results from the API are changing within the hour that the request is cached.
I’d be a bit pissed if I was requesting data from your app, the data had changed within the API, but your app kept serving me stale results for the next hour.
Instead, leverage actual HTTP caching. If the API is any good, it’ll expose a few headers in responses such as ETag and Last-Modified. You can save these values, and send them with subsequent requests.
If the API responds to a request with a 304 Not Modified status code, then you can serve your cached response (because the results are the same and haven’t changed since the last request). Otherwise, send the results to the user and cache that new response.
The API is for my website, not intended for external usage.
What I want to cache is not "critical" in terms of values. Like some grouping and counting of "objects" in the database. New objects are added constantly, but having those values up to date is not important, so if they are stale for 1 hour is fine.
I want to cache those queries results because the query is a bit heavy to compute, so rather than have each users wait 0.5s to compute it, it's better to have it cached and served immediately.
@swagger If this is your API and not a third-party one then, you can put a caching layer in between your Eloquent model calls.
Access your data via a repository, and wrap your repositories in one that caches the results. Leave your Eloquent models as just the data transport (reading/writing records) instead of trying to shoe-horn caching there.
Eloquent is an ORM; it’s not meant to be concerned with caching. That’s a concern of your application, not your ORM. If in the unlikely event you swap Eloquent for another ORM, then you’re going to have to re-do your caching logic again. The caching logic should be separated so that it doesn’t care where the data comes from; just that it caches the results for a certain length of time.
If you keep concerns separate (such as data retrieval and caching), then you’ll find your application is made up of code and classes that are much easier to maintain and reason about.