O
O
Oleg2021-03-26 15:30:08
OOP
Oleg, 2021-03-26 15:30:08

Can DTO(Data Transfer Object) have required properties via constructor?

As far as I understand, the essence of DTO is to replace a large number of arguments in a method with a more convenient structure. For example, to avoid such a situation function addUser(100, null, null, null, null, null, 'address'); Instead, create a DTO object, populate only the desired property, and pass only the object as an argument

. Can a DTO have a constructor that makes certain properties required to be populated? Or should all properties always be optional? If I need to have some mandatory parameters when creating my entity, and some not, then what should I do? Validate mandatory parameters already in the client code?

An example of my use of DTOs

class UserData {
  public $id;
  public $name;
  public $address;
 *и еще куча свойств*
}

class User {
  private $id;
  private $name;
  private $address;
  *и еще много свойств*

  __construct($id, $name, $address, *и еще много свойств*) {
    $this->id = $id;    
    $this->name = $name;    
    $this->address = address;    
  }

  *всякие геттеры и сеттеры*
}

class UserService {
  public function createUser(UserData $userData) {
    if(empty($userData->id)) {return false;}

    return new User(
      $userData->id,
      $userData->name,
      $userData->address
      *и еще там много полей*
    )
  }
}

class UserController()
{
  public function create($request) {
    *валидация реквеста*

   $user =  (new UserService())->create(new UserData(
     $request->id, 
     $request->name,
     $request->address,
     *другие данные*
   ))
  }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vasily Bannikov, 2021-03-26
@vabka

Yes, it can, and even should receive mandatory fields through a constructor or a factory method.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question