Skip to content

Instantly share code, notes, and snippets.

@wowo
Last active June 30, 2022 10:46
Show Gist options
  • Save wowo/b49ac45b975d5c489214 to your computer and use it in GitHub Desktop.
Save wowo/b49ac45b975d5c489214 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');
@Aerendir
Copy link

Aerendir commented Jul 6, 2015

Is there a Composer package of this so I can include it in my projects?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment