-
-
Save lifesign/7a17171bb0b6772a30a8f3676a28fcb7 to your computer and use it in GitHub Desktop.
This file contains 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