ldc-groupe/app/Traits/Models/HasCache.php
2025-12-15 14:30:45 +01:00

83 lines
2.1 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();
});
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
{
$class = static::class;
$cacheKey = static::getCacheKey();
Cache::forget($cacheKey);
static::getModelsCached();
}
/**
* Get all models cached.
*
* @return \Illuminate\Database\Eloquent\Collection<int,self>
*/
public static function getModelsCached(): \Illuminate\Database\Eloquent\Collection
{
$class = static::class;
$cacheKey = static::getCacheKey();
return Cache::remember($cacheKey, 86400, function () use ($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
*/
protected static function getCacheKey(): string
{
return 'cache_' . str_replace('\\', '_', static::class);
}
}