Skip to content

Instantly share code, notes, and snippets.

@defenestrator
Forked from nuernbergerA/cacheable.php
Created December 4, 2016 23:47
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save defenestrator/68576b62f786f07c5cb15d0898409a20 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($name, $arguments)
{
return Cache::remember($this->cacheName($name), $this->minutes * 60, function() use ($name, $arguments) {
if(count($arguments)==0){
return $this->model->$name();
};
return $this->model->$name($arguments);
});
}
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($name)
{
return Str::lower(
str_replace('\\','.',get_class($this->model)).'.'.$name
);
}
}
trait Cachable {
public static function cached($minutes=null)
{
return new CachedModel(new static, $minutes);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment