zenstruck / foundry

A model factory library for creating expressive, auto-completable, on-demand dev/test fixtures with Symfony and Doctrine.
https://symfony.com/bundles/ZenstruckFoundryBundle/current/index.html
MIT License
609 stars 63 forks source link

Wrong example for memoize in documentation #525

Closed mmarton closed 7 months ago

mmarton commented 7 months ago

Hi!

I just started using this lib and so far so good. But this bug costed me hours. In the docs at the memoize part the example sais:

protected function getDefaults(): array
    {
        $owner = LazyValue::memoize(fn () => UserFactory::new());

        return [
            // Call CategoryFactory::random() everytime this factory is instantiated
            'category' => LazyValue::new(fn() => CategoryFactory::random()),
            // The same User instance will be both added to the Project and set as the Task owner
            'project' => ProjectFactory::new(['users' => [$owner]]),
            'owner'   => $owner,
        ];
    }

but this way it actually creates 2 different User entities. What is should say is:

protected function getDefaults(): array
    {
        $owner = LazyValue::memoize(fn () => UserFactory::createOne()); // changed ::new() to ::createOne()

        return [
            // Call CategoryFactory::random() everytime this factory is instantiated
            'category' => LazyValue::new(fn() => CategoryFactory::random()),
            // The same User instance will be both added to the Project and set as the Task owner
            'project' => ProjectFactory::new(['users' => [$owner]]),
            'owner'   => $owner,
        ];
    }

this way only 1 User entity is created.

kbond commented 7 months ago

Ah crap, you're right, sorry about that. I've fixed in #526.