Z3d0X / filament-fabricator

Block-Based Page Builder Skeleton for your Filament Apps
https://filamentphp.com/plugins/fabricator
MIT License
270 stars 52 forks source link

Cache issue #49

Closed martin-ro closed 1 year ago

martin-ro commented 1 year ago

First of all, great plugin! Thanks for your work!

I noticed that queries in PageBlocks are fired every time you visit a page. Take for example this block:

public static function getBlockSchema(): Block
    {
        return Block::make('my-block')
            ->schema([
                Select::make('users')
                    ->options(User::pluck('name', 'id'))
            ]);
    }

    public static function mutateData(array $data): array
    {
        return array_merge($data, [
            'users' => Cache::remember('my_block_users', 60, function () use ($data) {
                return User::find($data['users']);
            }),
        ]);
    }

When visiting the page, the mutated data is cached but the query for theSelect (User::pluck('name', 'id')) field is still running every time.

Cheers, Martin

martin-ro commented 1 year ago

Ok, so investigating this further... in abstract class PageBlock

public static function getName(): string
    {
        return static::getBlockSchema()->getName();
    }

is called which causes the queries to be run. For now, I can get around it by implementing getName() in each of my blocks and just returning a string.

Z3d0X commented 1 year ago

Passing a closure to ->options() in Select ensures, that it is evaluated only when needed

Select::make('users')
    ->options(fn () => User::pluck('name', 'id'))
martin-ro commented 1 year ago

Ohhh... good catch! :)