| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091 |
- <?php
- namespace App\Module\User\Dto;
- use App\Module\User\Enums\STATUS2;
- use App\Module\User\Models\User;
- /**
- * 用户数据传输对象
- *
- * 用于在服务层返回用户信息,避免直接暴露模型对象
- */
- class UserDto
- {
- /**
- * @var int 用户ID
- */
- public int $id;
- /**
- * @var string 用户名
- */
- public string $username;
- /**
- * @var STATUS2 用户状态
- */
- public STATUS2 $status2;
- /**
- * @var string 创建时间
- */
- public string $createdAt;
- /**
- * @var string 更新时间
- */
- public string $updatedAt;
- /**
- * @var UserInfoDto|null 用户详细信息
- */
- public ?UserInfoDto $info = null;
- /**
- * 从模型创建DTO
- *
- * @param User $model 用户模型
- * @param bool $withInfo 是否包含用户详细信息
- * @return self
- */
- public static function fromModel(User $model, bool $withInfo = false): self
- {
- $dto = new self();
- $dto->id = $model->id;
- $dto->username = $model->username;
- $dto->status2 = $model->status2;
- $dto->createdAt = $model->created_at ? $model->created_at->toDateTimeString() : '';
- $dto->updatedAt = $model->updated_at ? $model->updated_at->toDateTimeString() : '';
- // 如果需要包含用户详细信息,并且模型已加载关联
- if ($withInfo && $model->relationLoaded('info') && $model->info) {
- $dto->info = UserInfoDto::fromModel($model->info);
- }
- return $dto;
- }
- /**
- * 转换为数组
- *
- * @return array
- */
- public function toArray(): array
- {
- $result = [
- 'id' => $this->id,
- 'username' => $this->username,
- 'status2' => $this->status2->value,
- 'status2_name' => $this->status2->name,
- 'created_at' => $this->createdAt,
- 'updated_at' => $this->updatedAt,
- ];
- if ($this->info !== null) {
- $result['info'] = $this->info->toArray();
- }
- return $result;
- }
- }
|