Skip to content

Instantly share code, notes, and snippets.

@nuernbergerA
Last active January 2, 2017 18:42
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save nuernbergerA/63cf228532a04519ac44000ea591c090 to your computer and use it in GitHub Desktop.
Save nuernbergerA/63cf228532a04519ac44000ea591c090 to your computer and use it in GitHub Desktop.
<?php
/*
//Normal query
User::all();
//Cached query (default 60min)
User::cached()->all();
//Cached query (5min)
User::cached(5)->all();
or declare a default cache time direct on your model
protected $minutesToCache = 30;
*/
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;
class CachedModel
{
protected $model;
protected $minutes;
public function __construct($model, $minutes)
{
$this->model = $model;
$this->minutes = $this->minutes($minutes);
}
public function __call($method, $parameters)
{
return Cache::remember($this->cacheName($method, $parameters), $this->minutes * 60, function() use ($method, $parameters) {
return $this->model->$method(...$parameters);
});
}
protected function minutes($minutes){
if($minutes==null || !is_numeric($minutes))
{
$minutes = (isset($this->model->minutesToCache) && is_numeric($this->model->minutesToCache)) ? $this->model->minutesToCache: 60; //fallback to 60 minutes
}
return $minutes;
}
protected function cacheName($method, $parameters)
{
return Str::lower(
str_replace('\\','.',get_class($this->model)) . '.' . $method
) . '.' . md5(serialize($parameters));
}
}
trait Cachable {
public static function cached($minutes=null)
{
return new CachedModel(new static, $minutes);
}
}
@defenestrator
Copy link

Thanks for this, it really suits my needs right now!

@nuernbergerA
Copy link
Author

nuernbergerA commented Jan 2, 2017

@defenestrator i never used this code, so im very happy someone can use it 👍

Keep in mind function cacheName($name) should include arguments (or at least a hashed value) to avoid bugged results

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment