ldc-groupe/app/Traits/Models/HasCache.php
2026-02-11 09:15:43 +01:00

83 lines
2.2 KiB
PHP

<?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();
});
if (method_exists(static::class, 'initializeSoftDeletes')) {
static::restored(function () {
self::resetCache();
});
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 () {
$class = static::class;
/** @var \Illuminate\Database\Eloquent\Model $class */
return $class::query()
->when(
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
*/
private static function getCacheKey(): string
{
return 'cache_' . str_replace('\\', '_', static::class);
}
}