Skip to content

Instantly share code, notes, and snippets.

@wtoalabi
Created May 31, 2019 14:03
Show Gist options
  • Save wtoalabi/b4432eb4d5d3e83aa2f74648b39deeff to your computer and use it in GitHub Desktop.
Save wtoalabi/b4432eb4d5d3e83aa2f74648b39deeff to your computer and use it in GitHub Desktop.
<?php
namespace App;
use Exception;
use Illuminate\Support\Collection;
use Illuminate\Contracts\Cache\Repository as Cache;
class CacheDirective
{
private static $keys = [];
public static function setUp($model){
ob_start();
static::$keys[] = $key = self::normalizeKey($model);
return static::has($key);
}
public static function tearDown(){
$key = array_pop(static::$keys);
$fragment = ob_get_clean();
return static::put($key, $fragment);
}
protected static function normalizeKey($item, $key = null)
{
if (is_string($item) || is_string($key)) {
return is_string($item) ? $item : $key;
}
if (is_object($item) && method_exists($item, 'getCacheKey')) {
return $item->getCacheKey();
}
if ($item instanceof Collection) {
return md5($item);
}
return new Exception('Could not determine an appropriate cache key.');
}
public static function put($key, $fragment) {
$key = static::normalizeCacheKey($key);
$cache = app(Cache::class);
return $cache
->tags('views')
->rememberForever($key, function () use ($fragment) {
return $fragment;
});
}
public static function has($key) {
$key = static::normalizeCacheKey($key);
$cache = app(Cache::class);
return $cache
->tags('views')
->has($key);
}
private static function normalizeCacheKey($key) {
if (is_object($key) && method_exists($key, 'getCacheKey')) {
return $key->getCacheKey();
}
return $key;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment