UserDto.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php
  2. namespace App\Module\User\Dto;
  3. use App\Module\User\Enums\STATUS2;
  4. use App\Module\User\Models\User;
  5. /**
  6. * 用户数据传输对象
  7. *
  8. * 用于在服务层返回用户信息,避免直接暴露模型对象
  9. */
  10. class UserDto
  11. {
  12. /**
  13. * @var int 用户ID
  14. */
  15. public int $id;
  16. /**
  17. * @var string 用户名
  18. */
  19. public string $username;
  20. /**
  21. * @var STATUS2 用户状态
  22. */
  23. public STATUS2 $status2;
  24. /**
  25. * @var string 创建时间
  26. */
  27. public string $createdAt;
  28. /**
  29. * @var string 更新时间
  30. */
  31. public string $updatedAt;
  32. /**
  33. * @var UserInfoDto|null 用户详细信息
  34. */
  35. public ?UserInfoDto $info = null;
  36. /**
  37. * 从模型创建DTO
  38. *
  39. * @param User $model 用户模型
  40. * @param bool $withInfo 是否包含用户详细信息
  41. * @return self
  42. */
  43. public static function fromModel(User $model, bool $withInfo = false): self
  44. {
  45. $dto = new self();
  46. $dto->id = $model->id;
  47. $dto->username = $model->username;
  48. $dto->status2 = $model->status2;
  49. $dto->createdAt = $model->created_at ? $model->created_at->toDateTimeString() : '';
  50. $dto->updatedAt = $model->updated_at ? $model->updated_at->toDateTimeString() : '';
  51. // 如果需要包含用户详细信息,并且模型已加载关联
  52. if ($withInfo && $model->relationLoaded('info') && $model->info) {
  53. $dto->info = UserInfoDto::fromModel($model->info);
  54. }
  55. return $dto;
  56. }
  57. /**
  58. * 转换为数组
  59. *
  60. * @return array
  61. */
  62. public function toArray(): array
  63. {
  64. $result = [
  65. 'id' => $this->id,
  66. 'username' => $this->username,
  67. 'status2' => $this->status2->value,
  68. 'status2_name' => $this->status2->name,
  69. 'created_at' => $this->createdAt,
  70. 'updated_at' => $this->updatedAt,
  71. ];
  72. if ($this->info !== null) {
  73. $result['info'] = $this->info->toArray();
  74. }
  75. return $result;
  76. }
  77. }