CityRepository.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. <?php
  2. namespace App\Repositories;
  3. use App\Models\City;
  4. use App\DTO\CityDTO;
  5. use Illuminate\Database\Eloquent\Collection;
  6. use Illuminate\Support\Facades\Cache;
  7. class CityRepository implements CityRepositoryInterface
  8. {
  9. public function __construct(
  10. protected City $model,
  11. readonly protected string $cacheKey = 'cities.all',
  12. readonly protected int $cacheTtl = 2592000 // one month in seconds
  13. ) {}
  14. public function all(): Collection
  15. {
  16. return Cache::remember($this->cacheKey, $this->cacheTtl, function () {
  17. return $this->model->with('state:id,name', 'country:id,name')->get();
  18. });
  19. }
  20. public function find(int $id): ?City
  21. {
  22. return $this->model->with('state:id,name', 'country:id,name')->find($id);
  23. }
  24. public function create(CityDTO $dto): City
  25. {
  26. Cache::forget($this->cacheKey);
  27. return $this->model->create($dto->toArray());
  28. }
  29. public function update(int $id, CityDTO $dto, array $fieldsToUpdate): City
  30. {
  31. $record = $this->find($id);
  32. $updateFields = array_intersect_key(
  33. $dto->toArray(),
  34. array_flip($fieldsToUpdate)
  35. );
  36. $record->update($updateFields);
  37. Cache::forget($this->cacheKey);
  38. return $record->fresh();
  39. }
  40. public function delete(int $id): bool
  41. {
  42. Cache::forget($this->cacheKey);
  43. return $this->model->destroy($id) > 0;
  44. }
  45. }