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); } }