auditionadmin/app/Services/EntryCacheService.php

76 lines
2.2 KiB
PHP

<?php
namespace App\Services;
use App\Models\Entry;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;
class EntryCacheService
{
protected $auditionCache;
/**
* Create a new class instance.
*/
public function __construct(AuditionCacheService $auditionCache)
{
$this->auditionCache = $auditionCache;
}
/**
* Return a collection of all entries for the provided auditionId along with the
* student.school for each entry.
* @param $auditionId
* @return \Illuminate\Database\Eloquent\Collection
*/
public function getEntriesForAudition($auditionId) {
// TODO this invokes a lot of lazy loading. Perhaps cache the data for all entries then draw from that for each audition
$cacheKey = 'audition' . $auditionId . 'entries';
return Cache::remember($cacheKey, 3600, function () use ($auditionId) {
return Entry::where('audition_id',$auditionId)
->with('student.school')
->get()
->keyBy('id');
});
}
/**
* Returns a collection of collections of entries, one collection for each audition.
* The outer collection is keyed by the audition ID. The included entries are
* with their student.school.
* @return Collection
*/
public function getAllEntriesByAudition(): Collection
{
$auditions = $this->auditionCache->getAuditions();
$allEntries = [];
foreach ($auditions as $audition) {
$allEntries[$audition->id] = $this->getEntriesForAudition($audition->id);
}
return collect($allEntries);
}
public function getAllEntries()
{
$cacheKey = 'allEntries';
return Cache::remember($cacheKey, 5, function() {
return Entry::all();
});
}
public function clearEntryCacheForAudition($auditionId): void
{
$cacheKey = 'audition' . $auditionId . 'entries';
Cache::forget($cacheKey);
Cache::forget('allEntries');
}
public function clearEntryCaches(): void
{
$auditions = $this->auditionCache->getAuditions();
foreach ($auditions as $audition) {
$this->clearEntryCacheForAudition($audition->id);
}
}
}