foundry icon indicating copy to clipboard operation
foundry copied to clipboard

It is better that \App\Factory\UserFactory::getDefaults return an entity object.

Open tourze opened this issue 3 years ago • 2 comments

Sample code:

    protected function getDefaults(): object
    {
        $entity = new User();
        $entity->setUsername(self::faker()->userName());
        // other properties...
        return $entity;
    }

I think it will be more readable and IDE friendly.

Now we can use a workaround method to do the same things, but it is better do it in the lib itself.

    // Inject Symfony\Component\Serializer\Normalizer\NormalizerInterface via constructor.

    protected function getDefaults(): object
    {
        $entity = new User();
        $entity->setUsername(self::faker()->userName());
        // other properties...
        return $this->normalizer->normalize($entity, 'array');
    }

tourze avatar Nov 17 '22 12:11 tourze

I do see what you are getting at here. Allowing objects here would certainly make renaming entity fields easier (with an IDE).

I don't see how we can achieve in a BC way though. The getDefaults() returning an array (or closure that returns an array) is meant to be merged with different factory states (which also return an array) and finally merged with the array passed to Factory::create(). This final array is then used to construct the object.

kbond avatar Nov 21 '22 15:11 kbond

my 2 cents here: while I think it could be a good idea, I don't see how we could have the same nice DX we have today in Foundry with this approach...

nikophil avatar Nov 23 '22 18:11 nikophil

I don't think we want to support this

nikophil avatar Jun 21 '24 15:06 nikophil