PHP值对象与数据传输对象值对象和数据传输对象是领域驱动设计中的重要概念。值对象描述不可变的数据DTO在不同层之间传输数据。今天说说它们的PHP实现。值对象是不可变的通过属性值来区分。phpclass Email{private string $value;public function __construct(string $value){if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {throw new InvalidArgumentException(无效的邮箱: $value);}$this-value $value;}public function getValue(): string { return $this-value; }public function equals(Email $other): bool{return $this-value $other-value;}public function __toString(): string{return $this-value;}}class Money{public function __construct(private readonly int $amount,private readonly string $currency CNY) {}public function add(Money $other): Money{if ($this-currency ! $other-currency) {throw new DomainException(货币不匹配);}return new Money($this-amount $other-amount, $this-currency);}public function getAmount(): int { return $this-amount; }public function getCurrency(): string { return $this-currency; }public function equals(Money $other): bool{return $this-amount $other-amount $this-currency $other-currency;}}$email1 new Email(testexample.com);$email2 new Email(testexample.com);var_dump($email1-equals($email2));$price new Money(1000);$tax new Money(130);$total $price-add($tax);echo $total-getAmount() . \n;?数据传输对象在不同层之间传递数据。phpclass UserDTO{public function __construct(public readonly int $id,public readonly string $name,public readonly string $email,public readonly ?string $phone null,public readonly ?array $roles null,public readonly ?string $createdAt null,) {}public static function fromArray(array $data): self{return new self(id: (int)$data[id],name: $data[name],email: $data[email],phone: $data[phone] ?? null,roles: $data[roles] ?? null,createdAt: $data[created_at] ?? null,);}public function toArray(): array{return [id $this-id,name $this-name,email $this-email,phone $this-phone,roles $this-roles,created_at $this-createdAt,];}}class OrderDTO{public function __construct(public readonly string $orderId,public readonly int $userId,public readonly float $total,public readonly string $status,public readonly array $items [],) {}}$userData [id 1, name 张三, email testtest.com];$userDTO UserDTO::fromArray($userData);echo $userDTO-name . \n;print_r($userDTO-toArray());?值对象和DTO让数据传递更安全。值对象封装了验证逻辑和不变性DTO明确定义了数据的结构。在PHP8中constructor property promotion和readonly让值对象和DTO的实现更简洁。