Created
January 5, 2017 09:44
-
-
Save ttomdewit/3cc6512c27950d643155e9cc83425da1 to your computer and use it in GitHub Desktop.
Trait for busting cache based on Eloquent events
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 | |
namespace App\Traits; | |
use Illuminate\Support\Facades\Cache; | |
trait CacheBuster | |
{ | |
public static function bootCacheBuster() | |
{ | |
foreach (static::getCacheEvents() as $event) { | |
static::$event(function ($model) { | |
$keys = static::getCacheKeys($model); | |
foreach ($keys as $key) { | |
Cache::forget($key); | |
} | |
}); | |
} | |
} | |
protected static function getCacheKeys($model) | |
{ | |
$keys = static::cacheKeys(); | |
$cacheKeys = []; | |
foreach ($keys as $key) { | |
$elements = explode('.', $key); | |
if (count($elements) > 1) { | |
$id = $elements[1]; | |
if (! is_null($model->$id)) { | |
$elements[1] = str_replace($id, $model->$id, $elements[1]); | |
} | |
} | |
$cacheKeys[] = implode('.', $elements); | |
} | |
return $cacheKeys; | |
} | |
protected static function getCacheEvents() | |
{ | |
if (isset(static::$cacheEvents)) { | |
return static::$cacheEvents; | |
} | |
return [ | |
'created', | |
'updated', | |
'deleted', | |
]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I normally use cache decoration on top of my repositories bound into the dependency container.
See a rough example at https://gist.github.com/joshbrw/6ddf41715cc3833eb64efb94543468a1