87 lines
2.4 KiB
PHP
87 lines
2.4 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();
|
|
});
|
|
/** @phpstan-ignore-next-line */
|
|
if (method_exists(static::class, 'initializeSoftDeletes')) {
|
|
/** @phpstan-ignore-next-line */
|
|
static::restored(function () {
|
|
self::resetCache();
|
|
});
|
|
/** @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 () {
|
|
/** @var class-string<static> $class */
|
|
$class = static::class;
|
|
/** @phpstan-ignore-next-line */
|
|
return $class::query()
|
|
->when(
|
|
/** @phpstan-ignore-next-line */
|
|
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
|
|
*/
|
|
public static function getCacheKey(): string
|
|
{
|
|
return sprintf("cache_%s", str_replace('\\', '_', static::class));
|
|
}
|
|
}
|