Files
portal-api/app/Services/Cache/CacheService.php
T
2025-08-24 22:41:15 +07:00

58 lines
1.4 KiB
PHP

<?php
namespace App\Services\Cache;
use App\Services\Caches\CacheServiceInterface;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
class CacheService implements CacheServiceInterface
{
protected int $ttl;
public function __construct(int $ttl = 60)
{
$this->ttl = $ttl;
}
public function putCache(string $prefix, string $key, mixed $value, ?int $ttl = null): void
{
$cacheKey = $this->makeKey($prefix, $key);
Cache::put($cacheKey, $value, $ttl ?? $this->ttl);
}
public function getCache(string $prefix, string $key, mixed $default = null): mixed
{
$cacheKey = $this->makeKey($prefix, $key);
return Cache::get($cacheKey, $default);
}
public function clearCache(string $prefix, string $key): void
{
$cacheKey = $this->makeKey($prefix, $key);
Cache::forget($cacheKey);
}
public function clearCacheByPrefix(string $prefix): void
{
$cachePrefix = config('cache.prefix');
$pattern = $cachePrefix . $prefix . '_*';
$keys = Redis::connection('cache')->keys($pattern);
foreach ($keys as $k) {
Redis::connection('cache')->del($k);
}
}
protected function makeKey(string $prefix, string $key = ''): string
{
return trim($prefix . '_' . $key, '_');
}
}