Files
portal-api/app/Repositories/BaseCachedRepository.php
T
2025-07-24 16:18:27 +07:00

82 lines
1.8 KiB
PHP

<?php
namespace App\Repositories;
use Illuminate\Support\Facades\Cache;
abstract class BaseCachedRepository extends BaseRepository
{
protected $cacheTime = 172800; // Thời gian lưu cache )giây)
public function __construct()
{
parent::__construct();
}
public function find($id)
{
$cacheKey = $this->getCacheKey($id);
return Cache::remember($cacheKey, $this->cacheTime, function () use ($id) {
return parent::find($id);
});
}
public function getAll()
{
$cacheKey = $this->getCacheKey("getAll");
return Cache::remember($cacheKey, $this->cacheTime, function () {
return parent::getAll();
});
}
public function create($data = [])
{
$result = parent::create($data);
$this->clearCache();
return $result;
}
public function insert(array $data = [])
{
$result = parent::insert($data);
$this->clearCache();
return $result;
}
public function update(int $id = 0, array $data = [])
{
$result = parent::update($id, $data);
$this->clearCache();
return $result;
}
public function delete($id)
{
$result = parent::delete($id);
$this->clearCache();
return $result;
}
protected function getCacheKey($method)
{
return sprintf('%s_%s', static::class, $method);
}
public function getCount()
{
$cacheKey = $this->getCacheKey("getCount");
return Cache::remember($cacheKey, $this->cacheTime, function () {
return parent::getCount();
});
}
public function clearCache()
{
Cache::flush();
}
public function clearCacheByKey(string $key)
{
$cacheKey = $this->getCacheKey($key);
Cache::forget($cacheKey);
}
}