Skip to content

Using a Command as DTO to populate Symfony Form #5

@webdevilopers

Description

@webdevilopers

@beberlei shows a good example on how to use this approach here:
http://whitewashing.de/2012/08/22/building_an_object_model__no_setters_allowed.html

With the following code you can add the EditPostCommand to the data_class of the EditPostType form:

<?php
class EditPostCommand
{
    public $id;
    public $headline;
    public $text;
    public $tags = array();
}
<?php
class PostController
{
    public function editAction(Request $request)
    {
        $post = $this->findPostViewModel($request->get('id'));

        // This could need some more automation/generic code
        $editPostCommand           = new EditPostCommand();
        $editPostCommand->id       = $request->get('id');
        $editPostCommand->headline = $post->headline;
        $editPostCommand->text     = $post->text;
        $editPostCommand->tags     = $post->tags;

        // here be the form framework handling...
        $form = $this->createForm(new EditPostType(), $editPostCommand);
        $form->bind($request);

        if (!$form->isValid()) {
            // invalid, show errors
        }

        // here we invoke the model, finally, through the service layer
        $this->postService->edit($editPostCommand);
    }
}

But it seems like Commands should be regarded immutable too which means the properties should not be public. Of course Symfony Form needs at least these to populate the Command.

@matthiasnoback has an interesting solution for this Symfony Form Use Case:
https://github.com/matthiasnoback/convenient-immutability

A Groovy example by @bodiam:
http://www.jworks.nl/2011/08/26/friday-repost-groovys-immutable-pitfalls/

General discussion:
https://groups.google.com/forum/#!msg/dddinphp/a5ielXU3EZg/qEoi5ppWAgAJ

Is there any approach how we could use the Command with Symfony Form if the properties were private?

Maybe using the empty_data callback on the Command / DTO and a static method as suggested by @webmozart:
http://whitewashing.de/2012/08/22/building_an_object_model__no_setters_allowed.html#comment-1091314235

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions