Last active
June 30, 2022 10:46
-
-
Save wowo/b49ac45b975d5c489214 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
final class EmailValueObject | |
{ | |
private $mailbox; | |
private $host; | |
public function __construct($email) | |
{ | |
if (false === strpos($email, '@')) { | |
throw new \InvalidArgumentException('This does not look like an email'); | |
} | |
list($this->mailbox, $this->host) = explode('@', $email); | |
} | |
public function __toString() | |
{ | |
return sprintf('%s@%s', $this->mailbox, $this->host); | |
} | |
public function __set($field, $value) | |
{ | |
} | |
public function changeMailbox($newMailbox) | |
{ | |
$copy = clone $this; | |
$copy->mailbox = $newMailbox; | |
return $copy; | |
} | |
} | |
// value object works as expected | |
$email = new EmailValueObject('[email protected]'); | |
assert((string) $email == '[email protected]'); | |
// new instance of value object is created as well | |
$changed = $email->changemailbox('wojtek'); | |
assert((string) $changed == '[email protected]'); | |
// old is not affected, hasn't been mutated | |
assert((string) $email == '[email protected]'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Is there a Composer package of this so I can include it in my projects?