diff --git a/README.md b/README.md index a79d6e6..fdcc259 100644 --- a/README.md +++ b/README.md @@ -49,7 +49,7 @@ mean that the entire cache is cleared each time a model is created, saved, updated, or deleted. For ease of maintenance, I would recommend adding a `BaseModel` model that -extends `CachedModel`, from which all your other models are extended. If you +uses `Cachable`, from which all your other models are extended. If you don't want to do that, simply extend your models directly from `CachedModel`. Here's an example `BaseModel` class: @@ -57,10 +57,11 @@ Here's an example `BaseModel` class: ```php forget('genealabs-laravel-model-caching-is-disabled'); - - return new EloquentBuilder($query); - } - - return new Builder($query); - } - - public static function boot() - { - parent::boot(); - - $class = get_called_class(); - $instance = new $class; - - static::created(function () use ($instance) { - $instance->flushCache(); - }); - - static::deleted(function () use ($instance) { - $instance->flushCache(); - }); - - static::saved(function () use ($instance) { - $instance->flushCache(); - }); - - static::updated(function () use ($instance) { - $instance->flushCache(); - }); - } - - public static function all($columns = ['*']) - { - $class = get_called_class(); - $instance = new $class; - $tags = [str_slug(get_called_class())]; - $key = $instance->makeCacheKey(); - - return $instance->cache($tags) - ->rememberForever($key, function () use ($columns) { - return parent::all($columns); - }); - } } diff --git a/src/Traits/Cachable.php b/src/Traits/Cachable.php index 3e16c37..11c00c2 100644 --- a/src/Traits/Cachable.php +++ b/src/Traits/Cachable.php @@ -5,6 +5,8 @@ use GeneaLabs\LaravelModelCaching\CachedModel; use Illuminate\Cache\TaggableStore; use Illuminate\Database\Query\Builder; +use Illuminate\Database\Eloquent\Builder as EloquentBuilder; +use GeneaLabs\LaravelModelCaching\CachedBuilder; trait Cachable { @@ -60,4 +62,35 @@ protected function makeCacheTags() : array return (new CacheTags($this->eagerLoad, $this->model)) ->make(); } + + public static function bootCachable() + { + static::saved(function ($instance) { + $instance->flushCache(); + }); + } + + public static function all($columns = ['*']) + { + $class = get_called_class(); + $instance = new $class; + $tags = [str_slug(get_called_class())]; + $key = $instance->makeCacheKey(); + + return $instance->cache($tags) + ->rememberForever($key, function () use ($columns) { + return parent::all($columns); + }); + } + + public function newEloquentBuilder($query) + { + if (session('genealabs-laravel-model-caching-is-disabled')) { + session()->forget('genealabs-laravel-model-caching-is-disabled'); + + return new EloquentBuilder($query); + } + + return new CachedBuilder($query); + } }