Last active
January 2, 2017 18:42
-
-
Save nuernbergerA/63cf228532a04519ac44000ea591c090 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($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 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
Thanks for this, it really suits my needs right now!