zendframework / zend-form

Form component from Zend Framework
BSD 3-Clause "New" or "Revised" License
69 stars 87 forks source link

WIP: Proposal: Empty object instantiator #212

Closed thomasvargiu closed 6 years ago

thomasvargiu commented 6 years ago

This PR is made to allow to create the object binded to a form only when form data are available.

Imagine the situation where you need to create a new User with a value-object like this:

class User
{
    public function __construct(string $username, Role $role)
    {
        $this->username = $username;
        $this->role = $role;
    }
}

To create the user we need to pass properties in constructor, so we can't create (and bind) it before to have some validated data from the form.

Of course the best way should be to use a data mapper, but this would be a convenient way to resolve this problem.

Proposal:

Add a callable to create the object only when object is empty and validated data are available.

Usage:

$form = new Form();
$form->setEmptyObjectInstantiator(function(array $data, Fieldset $fieldset) use ($entityManager) {  
    return new User(
        $data['username'],
        $entityManager->find(Role::class, $data['role'])
    );
});

Possible problems with the current implementation

Like for Form::bind(), in the setEmptyObjectInstantiator() we need to set the value even on the baseFieldset. To do this we should add the method in the Fieldset interface, but it would be a BC. Right now I check whether the method exists with method_exists().

Todo:

This is just the first idea on how to implement this feature, proposals and suggestions are welcome.

froschdesign commented 6 years ago

@thomasvargiu

Possible problems with the current implementation

…To do this we should add the method in the Fieldset interface…

I see another problem: the goal should be to remove / extract all methods that can bind an object to a form. This will reduce the complexity of the Fieldset and Form classes. Your suggestion will increase the complexity of the classes / interfaces. So it's the wrong direction!

thomasvargiu commented 6 years ago

I completely agree with you @froschdesign, working on it I saw too much complexity alredy existing. I'm going to close this PR.