store/app/Services/Concerns/CachesQuery.php

50 lines
1.1 KiB
PHP

<?php
namespace App\Services\Concerns;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Redis;
trait CachesQuery
{
protected function cacheRemember(string $key, int $ttl, callable $callback)
{
return Cache::remember($key, $ttl, $callback);
}
protected function cacheForever(string $key, callable $callback)
{
return Cache::rememberForever($key, $callback);
}
protected function cacheForget(string $key): void
{
Cache::forget($key);
}
protected function cacheForgetByPattern(string $pattern): void
{
if (config('cache.default') !== 'redis') {
Cache::flush();
return;
}
$redis = Redis::connection('cache');
$prefix = config('cache.prefix', 'laravel_cache');
$fullPattern = "{$prefix}:{$pattern}";
$cursor = null;
do {
[$cursor, $keys] = $redis->scan($cursor ?? 0, ['match' => $fullPattern, 'count' => 100]);
if (! empty($keys)) {
$redis->del($keys);
}
} while ($cursor);
}
}