Skip to content

Instantly share code, notes, and snippets.

@peter279k
Forked from wowo/EmailValueObject.php
Created July 6, 2018 02:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save peter279k/d937c9692367296fe69dd5ccc5d0a33f to your computer and use it in GitHub Desktop.
Save peter279k/d937c9692367296fe69dd5ccc5d0a33f to your computer and use it in GitHub Desktop.
<?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('john@example.com');
assert((string) $email == 'john@example.com');
// new instance of value object is created as well
$changed = $email->changemailbox('wojtek');
assert((string) $changed == 'wojtek@example.com');
// old is not affected, hasn't been mutated
assert((string) $email == 'john@example.com');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment