sysuser
PREMİUM
- Katılım
- 9 Kas 2025
- Mesajlar
- 174
- Tepki puanı
- 4
- Cinsiyet
- Kadın
PHP'de Immutable Value Object Pattern
Para birimi, koordinat, tarih aralığı gibi kavramları temsil eden nesneler değiştirilmemelidir. Immutable Value Object bu ihtiyacı karşılar.
Uygulama
PHP:
final class Money {
public function __construct(
public readonly int $amount,
public readonly string $currency,
) {}
public function add(Money $other): self {
if ($this->currency !== $other->currency) {
throw new InvalidArgumentException('Para birimi uyuşmuyor');
}
return new self($this->amount + $other->amount, $this->currency);
}
public function equals(Money $other): bool {
return $this->amount === $other->amount
&& $this->currency === $other->currency;
}
}
Neden Immutable?
- Nesne bir yerden geçtikten sonra beklenmedik biçimde değişmez
- Thread güvenlidir; paylaşılan durumdan kaynaklanacak hatalar oluşmaz
- Test etmek kolaylaşır; yan etkiler takip edilmez