B
B
BonBon Slick2021-09-01 01:16:24
Software design
BonBon Slick, 2021-09-01 01:16:24

Does it make sense to use constructors in DTO?

An example of a simple DTO

class UpdateUser extends AbstractRequestEntityDTO {
    public ?string         $authToken;
    public ?string         $email;
    public ?string         $description;
    public ?string         $fallbackEmail;
    public ?string         $slug;
    public ?string         $nickname;
    public ?string         $countryAlpha2;
    public ?string         $languageAlpha2;
    public ?string         $languageNativeName;
    public ?string         $countryNativeName;

    public function __construct(
        ?string $email = null,
        ?string $nickname = null,
        ?string $slug = null,
        ?string $fallbackEmail = null,
        ?string $countryAlpha2 = null,
        ?string $languageAlpha2 = null
    ) {
        $this->nickname       = $nickname;
        $this->email          = $email;
        $this->fallbackEmail  = $fallbackEmail;
        $this->slug           = $slug;
        $this->countryAlpha2  = $countryAlpha2;
        $this->languageAlpha2 = $languageAlpha2;
    }


Usually 5-8 fields, rarely more or less, but the question arises, for example, it is unlikely that in order to set a slug in the DTO we will use the constructor, but it will be like this

new UpdateUser (null,null,null,null,null,null,'newNickname');


when it's easier to do static factories
UpdateUser::fromRequest($request)
but this approach is unsafe
I tend to the builder
(new UpdateUser)->setNickname($request->request->get('nickname'))->setOtherFields();


But here the question arises, does it make sense then to use constructors for DTOs?

How do you do it and why?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Gordinskiy, 2021-09-01
@BonBonSlick

and nothing it will be like this

Named arguments to help:
new UpdateUser(nickname: 'newNickname');

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question