PHP值对象与数据传输对象
PHP值对象与数据传输对象
值对象和数据传输对象是领域驱动设计中的重要概念。值对象描述不可变的数据,DTO在不同层之间传输数据。今天说说它们的PHP实现。
值对象是不可变的,通过属性值来区分。
```php
class 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('test@example.com');
$email2 = new Email('test@example.com');
var_dump($email1->equals($email2));
$price = new Money(1000);
$tax = new Money(130);
$total = $price->add($tax);
echo $total->getAmount() . "\n";
?>
数据传输对象在不同层之间传递数据。
```php
class 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' => 'test@test.com'];
$userDTO = UserDTO::fromArray($userData);
echo $userDTO->name . "\n";
print_r($userDTO->toArray());
?>
值对象和DTO让数据传递更安全。值对象封装了验证逻辑和不变性,DTO明确定义了数据的结构。在PHP8中,constructor property promotion和readonly让值对象和DTO的实现更简洁。
AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。
更多推荐

所有评论(0)