Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion docs/content/2.essentials/1.configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
26 changes: 26 additions & 0 deletions src/Console/Commands/ClearCacheCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

declare(strict_types=1);

namespace Relaticle\CustomFields\Console\Commands;

use Illuminate\Console\Command;
use Relaticle\CustomFields\EntitySystem\EntityManager;

final class ClearCacheCommand extends Command
{
/** @var string */
protected $signature = 'custom-fields:clear-cache';

/** @var string */
protected $description = 'Clear the cached custom fields entity registry';

public function handle(EntityManager $entityManager): int
{
$entityManager->clearCache();

$this->components->info('Custom fields entity cache cleared.');

return self::SUCCESS;
}
}
2 changes: 2 additions & 0 deletions src/CustomFieldsServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -177,6 +178,7 @@ private function getCommands(): array
{
return [
CleanupOrphanedValuesCommand::class,
ClearCacheCommand::class,
MakeCustomFieldsMigrationCommand::class,
MakeFieldTypeCommand::class,
UpgradeCommand::class,
Expand Down
10 changes: 1 addition & 9 deletions src/EntitySystem/EntityDiscovery.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,6 @@

final class EntityDiscovery
{
private array $discoveredCache = [];

public function __construct(
private array $paths = [],
private array $namespaces = []
Expand All @@ -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)
Expand All @@ -73,9 +67,7 @@ public function discover(): array
}
}

$this->discoveredCache = array_values($entities);

return $this->discoveredCache;
return array_values($entities);
}

/**
Expand Down
47 changes: 35 additions & 12 deletions src/EntitySystem/EntityManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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<string, array<string, EntityConfigurationData>> */
private array $cachedEntities = [];

private ?EntityDiscovery $discovery = null;

Expand All @@ -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,
) {}

/**
Expand All @@ -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]);
}

/**
Expand Down Expand Up @@ -107,7 +111,7 @@ public function disableDiscovery(): static
*/
private function invalidateCache(): void
{
$this->cachedEntities = null;
$this->cachedEntities = [];
}

/**
Expand All @@ -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
*/
Expand Down
3 changes: 2 additions & 1 deletion src/Providers/EntityServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -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,
);
});

Expand Down
97 changes: 97 additions & 0 deletions tests/Feature/EntityRegistryCacheTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
<?php

declare(strict_types=1);

use Filament\Facades\Filament;
use Filament\Panel;
use Filament\PanelRegistry;
use Illuminate\Support\Facades\Cache;
use Relaticle\CustomFields\Contracts\EntityManagerInterface;
use Relaticle\CustomFields\EntitySystem\EntityConfigurator;
use Relaticle\CustomFields\EntitySystem\EntityManager;
use Relaticle\CustomFields\Tests\Fixtures\Models\Post;
use Relaticle\CustomFields\Tests\Fixtures\Resources\Posts\PostResource;

beforeEach(function (): void {
app(PanelRegistry::class)->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();
});
Loading