diff --git a/docs/content/2.essentials/1.configuration.md b/docs/content/2.essentials/1.configuration.md index ebc2d53cf..8e03b05cc 100644 --- a/docs/content/2.essentials/1.configuration.md +++ b/docs/content/2.essentials/1.configuration.md @@ -297,12 +297,18 @@ Optimize for production: ```php 'entity_configuration' => EntityConfigurator::configure() ->discover(app_path('Models')) - ->cache(env('CUSTOM_FIELDS_CACHE', true)), // Enable caching + ->cache(env('CUSTOM_FIELDS_CACHE', true), ttl: 3600), // Cache the entity registry for an hour 'field_type_configuration' => FieldTypeConfigurator::configure() ->cache(enabled: true, ttl: 3600), // Cache field types ``` +The entity registry is cached once per Filament panel, because discovery reads each panel's own resources. Clear it on every deploy so a changed `entity_configuration` takes effect at once. The command clears the entity registry only: + +```bash +php artisan custom-fields:clear-cache +``` + ### Multi-Tenancy Setup Enable tenant isolation: diff --git a/src/Console/Commands/ClearCacheCommand.php b/src/Console/Commands/ClearCacheCommand.php new file mode 100644 index 000000000..8ef9a16a2 --- /dev/null +++ b/src/Console/Commands/ClearCacheCommand.php @@ -0,0 +1,26 @@ +clearCache(); + + $this->components->info('Custom fields entity cache cleared.'); + + return self::SUCCESS; + } +} diff --git a/src/CustomFieldsServiceProvider.php b/src/CustomFieldsServiceProvider.php index df9c83d1e..7eabb42eb 100644 --- a/src/CustomFieldsServiceProvider.php +++ b/src/CustomFieldsServiceProvider.php @@ -14,6 +14,7 @@ use Illuminate\Filesystem\Filesystem; use Livewire\Livewire; use Relaticle\CustomFields\Console\Commands\CleanupOrphanedValuesCommand; +use Relaticle\CustomFields\Console\Commands\ClearCacheCommand; use Relaticle\CustomFields\Console\Commands\MakeCustomFieldsMigrationCommand; use Relaticle\CustomFields\Console\Commands\MakeFieldTypeCommand; use Relaticle\CustomFields\Console\Commands\UpgradeCommand; @@ -177,6 +178,7 @@ private function getCommands(): array { return [ CleanupOrphanedValuesCommand::class, + ClearCacheCommand::class, MakeCustomFieldsMigrationCommand::class, MakeFieldTypeCommand::class, UpgradeCommand::class, diff --git a/src/EntitySystem/EntityDiscovery.php b/src/EntitySystem/EntityDiscovery.php index 8f799987e..592da7784 100644 --- a/src/EntitySystem/EntityDiscovery.php +++ b/src/EntitySystem/EntityDiscovery.php @@ -21,8 +21,6 @@ final class EntityDiscovery { - private array $discoveredCache = []; - public function __construct( private array $paths = [], private array $namespaces = [] @@ -43,10 +41,6 @@ public function __construct( */ public function discover(): array { - if ($this->discoveredCache !== []) { - return $this->discoveredCache; - } - $entities = []; // 1. Discover from Filament Resources (highest priority) @@ -73,9 +67,7 @@ public function discover(): array } } - $this->discoveredCache = array_values($entities); - - return $this->discoveredCache; + return array_values($entities); } /** diff --git a/src/EntitySystem/EntityManager.php b/src/EntitySystem/EntityManager.php index 8f874a140..353662d81 100644 --- a/src/EntitySystem/EntityManager.php +++ b/src/EntitySystem/EntityManager.php @@ -8,6 +8,8 @@ namespace Relaticle\CustomFields\EntitySystem; use Closure; +use Filament\Exceptions\NoDefaultPanelSetException; +use Filament\Facades\Filament; use Filament\Resources\Resource; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Traits\Macroable; @@ -21,11 +23,12 @@ final class EntityManager implements EntityManagerInterface private const string CACHE_KEY = 'custom_fields_entities'; - private const int CACHE_TTL = 3600; // 1 hour + private const string NO_PANEL = 'no-panel'; private array $entities = []; - private ?array $cachedEntities = null; + /** @var array> */ + private array $cachedEntities = []; private ?EntityDiscovery $discovery = null; @@ -34,7 +37,8 @@ final class EntityManager implements EntityManagerInterface private array $resolvingCallbacks = []; public function __construct( - private readonly bool $cacheEnabled = true + private readonly bool $cacheEnabled = true, + private readonly int $cacheTtl = 3600, ) {} /** @@ -53,13 +57,13 @@ public function register(array|Closure $entities): static */ public function getEntities(): EntityCollection { - if ($this->cachedEntities === null) { - $this->cachedEntities = $this->cacheEnabled - ? Cache::remember(self::CACHE_KEY, self::CACHE_TTL, fn (): array => $this->buildEntityCache()) - : $this->buildEntityCache(); - } + $panelId = $this->currentPanelId(); + + $this->cachedEntities[$panelId] ??= $this->cacheEnabled + ? Cache::remember($this->cacheKey($panelId), $this->cacheTtl, fn (): array => $this->buildEntityCache()) + : $this->buildEntityCache(); - return new EntityCollection($this->cachedEntities); + return new EntityCollection($this->cachedEntities[$panelId]); } /** @@ -107,7 +111,7 @@ public function disableDiscovery(): static */ private function invalidateCache(): void { - $this->cachedEntities = null; + $this->cachedEntities = []; } /** @@ -117,13 +121,32 @@ public function clearCache(): static { $this->invalidateCache(); - if ($this->cacheEnabled) { - Cache::forget(self::CACHE_KEY); + if (! $this->cacheEnabled) { + return $this; + } + + foreach ([...array_keys(Filament::getPanels()), self::NO_PANEL] as $panelId) { + Cache::forget($this->cacheKey($panelId)); } return $this; } + // Discovery reads the current panel's resources, so each panel caches its own registry. + private function cacheKey(string $panelId): string + { + return self::CACHE_KEY.':'.$panelId; + } + + private function currentPanelId(): string + { + try { + return Filament::getCurrentOrDefaultPanel()?->getId() ?? self::NO_PANEL; + } catch (NoDefaultPanelSetException) { + return self::NO_PANEL; + } + } + /** * Get entities for a specific feature */ diff --git a/src/Providers/EntityServiceProvider.php b/src/Providers/EntityServiceProvider.php index d0674a4bb..7eca2fb91 100644 --- a/src/Providers/EntityServiceProvider.php +++ b/src/Providers/EntityServiceProvider.php @@ -24,7 +24,8 @@ public function register(): void $config = $this->getEntityConfig(); return new EntityManager( - cacheEnabled: $config['cache_entities'] ?? true + cacheEnabled: $config['cache_entities'] ?? true, + cacheTtl: $config['cache_ttl'] ?? 3600, ); }); diff --git a/tests/Feature/EntityRegistryCacheTest.php b/tests/Feature/EntityRegistryCacheTest.php new file mode 100644 index 000000000..e882cfea3 --- /dev/null +++ b/tests/Feature/EntityRegistryCacheTest.php @@ -0,0 +1,97 @@ +register(Panel::make()->id('portal')); + + useCachedResourceDiscovery(ttl: 600); +}); + +function useCachedResourceDiscovery(int $ttl): void +{ + config()->set('custom-fields.entity_configuration', + EntityConfigurator::configure() + ->discover([]) + ->cache(true, $ttl) + ); + + rebuildEntityManager(); +} + +function rebuildEntityManager(): EntityManager +{ + app()->forgetInstance(EntityManager::class); + app()->forgetInstance(EntityManagerInterface::class); + + return app(EntityManager::class); +} + +function entitiesSeenInPanel(string $panelId): EntityManager +{ + Filament::setCurrentPanel($panelId); + + return rebuildEntityManager(); +} + +it('serves each panel the registry built from its own resources', function (): void { + expect(entitiesSeenInPanel('portal')->hasEntity(Post::class))->toBeFalse(); + + expect(entitiesSeenInPanel('admin')->getEntity(Post::class)?->getResourceClass())->toBe(PostResource::class); + + expect(entitiesSeenInPanel('portal')->hasEntity(Post::class))->toBeFalse(); +}); + +it('keeps panels apart within one long-lived manager', function (): void { + $manager = entitiesSeenInPanel('admin'); + $postAlias = $manager->getEntity(Post::class)?->getAlias(); + + expect($postAlias)->not->toBeNull(); + + $manager->clearCache(); + Filament::setCurrentPanel('portal'); + + expect($manager->hasEntity(Post::class))->toBeFalse() + ->and(Cache::get('custom_fields_entities:portal'))->not->toHaveKey($postAlias); + + Filament::setCurrentPanel('admin'); + + expect($manager->getEntity(Post::class)?->getResourceClass())->toBe(PostResource::class); +}); + +it('stores the registry for the configured ttl', function (): void { + useCachedResourceDiscovery(ttl: 120); + + entitiesSeenInPanel('admin')->getEntities(); + + $this->travel(119)->seconds(); + expect(Cache::has('custom_fields_entities:admin'))->toBeTrue(); + + $this->travel(2)->seconds(); + expect(Cache::has('custom_fields_entities:admin'))->toBeFalse(); +}); + +it('clears the cached registry of every panel', function (): void { + entitiesSeenInPanel('admin')->getEntities(); + entitiesSeenInPanel('portal')->getEntities(); + + expect(Cache::has('custom_fields_entities:admin'))->toBeTrue() + ->and(Cache::has('custom_fields_entities:portal'))->toBeTrue(); + + $this->artisan('custom-fields:clear-cache') + ->expectsOutputToContain('Custom fields entity cache cleared.') + ->assertSuccessful(); + + expect(Cache::has('custom_fields_entities:admin'))->toBeFalse() + ->and(Cache::has('custom_fields_entities:portal'))->toBeFalse(); +});