Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cache issue #49

Closed
martin-ro opened this issue Mar 1, 2023 · 3 comments
Closed

Cache issue #49

martin-ro opened this issue Mar 1, 2023 · 3 comments

Comments

@martin-ro
Copy link

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
Copy link
Author

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
Copy link
Owner

Z3d0X commented Mar 1, 2023

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
Copy link
Author

Ohhh... good catch! :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants