I have a model that never changes so I want to cache it. We access the data in a lot of different files and I don't want to repeat Cache::rememberForever(...) all over the place. So I centralized it in the model inside a function called allCached().
Here is my function in the model:
public static function allCached() {
return \Cache::rememberForever('categories', function() {
return Category::all();
});
}
Then I call it in multiple controllers like this:
$categories = Catagory::allCached();
I get the feeling this is a bad way to do it. I'm not really sure how to improve this. What is a better way of doing this?
@alanreed I agree with you. It's not a good approach to touch the default model.
Instead what I suggest you to use the boot() method in the Category model.
class Category extends Model
{
public static function boot()
{
parent::boot();
static::retrieved(function ($model) {
Cache::rememberForever('categories', function() use ($model) {
return $model;
});
});
}
}
@alanreed If you're in search of an optimized solution, I highly recommend following @snapey's suggestion. I also believe it's the right way to do that.
However, if you still choose to proceed with caching the entire model, then it would be wise to at least set a specific caching time frame.
I agree with @snapey but this is how you can do that. I would recommend caching the attrs.
override the all() method in the model using cache rememberforever:
public static function all() {
return static::cacheForever('categories', function() {
return Category::all();
});
}
public static function cacheForever($key, $callback) {
return \Cache::rememberForever($key, $callback);
}
This way, if you need to change the caching logic in the future, you only need to update the cacheForever method, instead of having to change it in multiple places.