90 lines
2.5 KiB
PHP
90 lines
2.5 KiB
PHP
<?php
|
|
|
|
namespace App\Repositories;
|
|
|
|
use App\Services\Cache\CacheServiceInterface;
|
|
use App\Support\Cache\CacheKey;
|
|
|
|
abstract class BaseCachedRepository extends BaseRepository
|
|
{
|
|
protected int $cacheTime = 172800; // 48 hours (fallback for raw Cache calls)
|
|
|
|
protected CacheServiceInterface $cache;
|
|
|
|
public function __construct()
|
|
{
|
|
parent::__construct();
|
|
$this->cache = app(CacheServiceInterface::class);
|
|
}
|
|
|
|
public function find($id)
|
|
{
|
|
$key = CacheKey::build($this->getModuleName(), 'find', ['id' => $id]);
|
|
|
|
return $this->cache->remember($key, fn () => parent::find($id), CacheServiceInterface::TTL_LONG);
|
|
}
|
|
|
|
public function create($data = [])
|
|
{
|
|
$result = parent::create($data);
|
|
$this->cache->clearByModule($this->getModuleName());
|
|
return $result;
|
|
}
|
|
|
|
public function insert(array $data = [])
|
|
{
|
|
$result = parent::insert($data);
|
|
$this->cache->clearByModule($this->getModuleName());
|
|
return $result;
|
|
}
|
|
|
|
public function update(int $id = 0, array $data = [])
|
|
{
|
|
$result = parent::update($id, $data);
|
|
$this->cache->clearByModule($this->getModuleName());
|
|
return $result;
|
|
}
|
|
|
|
public function delete($id)
|
|
{
|
|
$result = parent::delete($id);
|
|
$this->cache->clearByModule($this->getModuleName());
|
|
return $result;
|
|
}
|
|
|
|
public function clearCache(): void
|
|
{
|
|
$this->cache->clearByModule($this->getModuleName());
|
|
}
|
|
|
|
public function clearCacheByKey(string $key): void
|
|
{
|
|
$this->cache->forget(CacheKey::build($this->getModuleName(), $key));
|
|
}
|
|
|
|
// -------------------------------------------------------------------------
|
|
// Helpers for child repositories
|
|
// -------------------------------------------------------------------------
|
|
|
|
protected function rememberFilter(array $params, callable $query): mixed
|
|
{
|
|
$key = CacheKey::build($this->getModuleName(), 'filter', [
|
|
'hash' => md5(serialize($params)),
|
|
]);
|
|
|
|
return $this->cache->remember($key, $query, CacheServiceInterface::TTL_LONG);
|
|
}
|
|
|
|
protected function getModuleName(): string
|
|
{
|
|
$shortName = class_basename(static::class);
|
|
return strtolower(str_replace('CachedRepository', '', $shortName));
|
|
}
|
|
|
|
// Keep for backward compat — child classes that still call getCacheKey() directly.
|
|
protected function getCacheKey(string $suffix): string
|
|
{
|
|
return CacheKey::build($this->getModuleName(), $suffix);
|
|
}
|
|
}
|