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
646 stars 71 forks source link

DI support for ModelFactory class #32

Closed degausserx closed 3 years ago

degausserx commented 4 years ago

There is no Dependency Injection support when initializing a new ModelFactory with the new() method. I came upon this problem very early on when creating a User factory because I was unable to inject the PasswordEncoderInterface service into the factory. This meant I couldn't contain all logic involved in creating a new User inside the factory.

Any plans to address this?

kbond commented 4 years ago

Hey @degausserx! Funny, @weaverryan and I were just talking about this the other day. This was the use-case Ryan had as well.

In what context are you using Foundry? For fixtures or in your tests?


What I do for my UserFactory's, is "pre-hash" the password:

class UserFactory extends ModelFactory
{
    protected function getDefaults(): array
    {
        return [
            'username' => self::faker()->unique()->userName,
            'email' => self::faker()->unique()->safeEmail,
            'password' => '$argon2id$v=19$m=10,t=3,p=1$K9AFR15goJiUD6AdpK0a6Q$RsP6y+FRnYUBovBmhVZO7wN6Caj2eI8dMTnm3+5aTxk', // 1234
        ];
    }
}

You would have to remember the password for every user created with foundry is "1234" (a DEFAULT_PASSWORD constant could help here).

This also adds a significant performance boost if using in tests.

Could this work for you?

kbond commented 3 years ago

@degausserx, what do you think of #53? Think it will work for you?

walva commented 3 years ago

Hello @kbond,

Thank you for your work. It is indeed what I expected. I was discussing this with my colleague where this bundle was a no-go because of this. Now I can reconsider using this bundle in our app.