| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455 |
- <?php
- namespace App\Repositories;
- use App\Models\City;
- use App\DTO\CityDTO;
- use Illuminate\Database\Eloquent\Collection;
- use Illuminate\Support\Facades\Cache;
- class CityRepository implements CityRepositoryInterface
- {
- public function __construct(
- protected City $model,
- readonly protected string $cacheKey = 'cities.all',
- readonly protected int $cacheTtl = 2592000 // one month in seconds
- ) {}
- public function all(): Collection
- {
- return Cache::remember($this->cacheKey, $this->cacheTtl, function () {
- return $this->model->with('state:id,name', 'country:id,name')->get();
- });
- }
- public function find(int $id): ?City
- {
- return $this->model->with('state:id,name', 'country:id,name')->find($id);
- }
- public function create(CityDTO $dto): City
- {
- Cache::forget($this->cacheKey);
- return $this->model->create($dto->toArray());
- }
- public function update(int $id, CityDTO $dto, array $fieldsToUpdate): City
- {
- $record = $this->find($id);
- $updateFields = array_intersect_key(
- $dto->toArray(),
- array_flip($fieldsToUpdate)
- );
- $record->update($updateFields);
- Cache::forget($this->cacheKey);
- return $record->fresh();
- }
- public function delete(int $id): bool
- {
- Cache::forget($this->cacheKey);
- return $this->model->destroy($id) > 0;
- }
- }
|