ldc-groupe/app/Traits/Models/HasCache.php

88 lines
2.4 KiB
PHP
Raw Permalink Normal View History

<?php
namespace App\Traits\Models;
use Illuminate\Support\Facades\Cache;
/**
* If there is a static function in a trait (named boot[TraitName]),
* it will be executed as the boot() function would on an Eloquent model.
* Futhermore, event in the Model observer doesn't erase actual events in the model,
* but adds them.
*/
trait HasCache
{
/**
* Perform any actions required after the model boots.
*
* @return void
*/
public static function bootHasCache(): void
{
static::created(function () {
self::resetCache();
});
static::updated(function () {
self::resetCache();
});
static::deleted(function () {
self::resetCache();
});
2026-02-12 17:14:08 +01:00
/** @phpstan-ignore-next-line */
if (method_exists(static::class, 'initializeSoftDeletes')) {
2026-02-12 17:14:08 +01:00
/** @phpstan-ignore-next-line */
static::restored(function () {
self::resetCache();
});
2026-02-12 17:14:08 +01:00
/** @phpstan-ignore-next-line */
static::forceDeleted(function () {
self::resetCache();
});
}
}
/**
* Reset all cache elements related to this model.
*
* @return void
*/
public static function resetCache(): void
{
Cache::forget(static::getCacheKey());
static::getModelsCached();
}
/**
* Get all models cached.
*
* @return \Illuminate\Database\Eloquent\Collection<int,self>
*/
public static function getModelsCached(): \Illuminate\Database\Eloquent\Collection
{
return Cache::remember(static::getCacheKey(), 86400, function () {
2026-02-12 17:14:08 +01:00
/** @var class-string<static> $class */
$class = static::class;
2026-02-12 17:14:08 +01:00
/** @phpstan-ignore-next-line */
return $class::query()
2026-02-10 15:43:47 +01:00
->when(
2026-02-12 17:14:08 +01:00
/** @phpstan-ignore-next-line */
2026-02-10 15:43:47 +01:00
property_exists($class, 'cacheRelations') && is_array($class::$cacheRelations),
function ($query) use ($class) {
$query->with($class::$cacheRelations);
}
)
->get();
});
}
/**
* Generate a unique cache key for the model.
*
* @return string
*/
2026-02-12 17:14:08 +01:00
public static function getCacheKey(): string
{
2026-02-12 17:14:08 +01:00
return sprintf("cache_%s", str_replace('\\', '_', static::class));
}
}