Что такое Value Object? Как реализовать?

Ответ
// Value Object - неизменяемый объект, сравнивается по значению
readonly class Money {
    public function __construct(
        public int $amount,      // в копейках
        public string $currency,
    ) {
        if ($amount < 0) throw new InvalidArgumentException('Negative amount');
    }

    public function add(Money $other): self {
        if ($this->currency !== $other->currency) {
            throw new DomainException('Currency mismatch');
        }
        return new self($this->amount + $other->amount, $this->currency);
    }

    public function equals(Money $other): bool {
        return $this->amount === $other->amount
            && $this->currency === $other->currency;
    }
}

Ключевые свойства VO: иммутабельность, сравнение по значению (не по ссылке), самовалидация.

🧠Квиз 🏆Лидеры 🎯Собесед. 📖Вопросы 📚База зн.