Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eloquent (without Laravel) caching implementation

I am using Eloquent without Laravel and I'm wondering if there's a method which can be used (and does not rely on Laravel components) to integrate a caching method which then automatically caches all model queries (caching backend can be variable, say APCu or memcache).

I'm thinking that it should be possible to write a model base class which handles this but I'm not quite sure how I would go about implementing this. Does anybody have any ideas in this direction?

like image 860
user13955 Avatar asked Aug 03 '16 17:08

user13955


1 Answers

If you want to auto cache your query, you have to override the find(), findOrFail() , where() ... methods

Because of how Eloquent is built you can't simply add a method find() in your custom model class

https://laracasts.com/discuss/channels/eloquent/override-find-method/replies/72028

class MyCacheModel extends \Illuminate\Database\Eloquent\Model
{
// override methods as explained in previous link
// cache the result in redis for how long you want
}

Then in your model instead of extending Eloquent\Model, extends now from your MyCacheModel. With a bit of customization you can set how long queries will be cached and if a model shouldn't be cached then just use the Eloquent\Model.

like image 113
Sylwit Avatar answered Sep 27 '22 20:09

Sylwit