ldc-cocotte/app/Traits/Models/IsCachedAsCollection.php

89 lines
2.1 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Traits\Models;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\Cache;
/**
* ! Use this only on limited elements (not on tags, products, or posts, for example).
*
* @template TModel of \Illuminate\Database\Eloquent\Model
*
* @phpstan-require-extends \Illuminate\Database\Eloquent\Model
*
* @mixin \Illuminate\Database\Eloquent\Model
*/
trait IsCachedAsCollection
{
public static function bootIsCachedAsCollection(): void
{
$flush = static fn () => static::removeCached();
static::saved($flush);
static::deleted($flush);
}
/**
* @return Collection<int, TModel>
*/
public static function getCached(): Collection
{
return Cache::remember(
static::getCacheKeyName(),
48 * 60 * 60,
function () {
$query = static::query();
$cacheConditions = static::getCacheConditions();
if ($cacheConditions !== []) {
$query->where($cacheConditions);
}
$results = static::queryCached($query)->get();
return static::filterQuery($results);
}
);
}
public static function removeCached(): void
{
Cache::forget(static::getCacheKeyName());
}
/**
* @return array<string, string|int|float|bool>
*/
protected static function getCacheConditions(): array
{
return [];
}
/**
* @param Builder<TModel> $query
* @return Builder<TModel>
*/
protected static function queryCached(Builder $query): Builder
{
return $query;
}
/**
* @param Collection<int, TModel> $results
* @return Collection<int, TModel>
*/
protected static function filterQuery(Collection $results): Collection
{
return $results;
}
protected static function getCacheKeyName(): string
{
return 'model_cache_' . strtolower(class_basename(static::class));
}
}