92 lines
2.2 KiB
PHP
92 lines
2.2 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();
|
|
Cache::forget($this->getCacheKey($id));
|
|
return $result;
|
|
}
|
|
|
|
public function delete($id)
|
|
{
|
|
$result = parent::delete($id);
|
|
$this->clearCache();
|
|
Cache::forget($this->getCacheKey($id));
|
|
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()
|
|
{
|
|
// Chỉ xóa cache của repository này, không flush toàn bộ cache app
|
|
$keysToForget = [
|
|
$this->getCacheKey('getAll'),
|
|
$this->getCacheKey('getCount'),
|
|
];
|
|
|
|
foreach ($keysToForget as $key) {
|
|
Cache::forget($key);
|
|
}
|
|
}
|
|
public function clearCacheByKey(string $key)
|
|
{
|
|
$cacheKey = $this->getCacheKey($key);
|
|
|
|
Cache::forget($cacheKey);
|
|
}
|
|
}
|