-
-
Save defenestrator/68576b62f786f07c5cb15d0898409a20 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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