Last active
July 29, 2020 10:13
-
-
Save bwaidelich/ebc348200c859f0fa5b6c26330108337 to your computer and use it in GitHub Desktop.
Serializable Value Object
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 Customer implements \JsonSerializable | |
{ | |
private CustomerId $id; | |
private FullName $name; | |
public function __construct(CustomerId $id, FullName $name) | |
{ | |
$this->id = $id; | |
$this->name = $name; | |
} | |
public function id(): CustomerId | |
{ | |
return $this->id; | |
} | |
public function name(): FullName | |
{ | |
return $this->name; | |
} | |
public function jsonSerialize(): array | |
{ | |
return get_object_vars($this); | |
} | |
} |
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 CustomerId implements \JsonSerializable | |
{ | |
private string $value; | |
/** | |
* @var self[] | |
*/ | |
private static array $instances = []; | |
private function __construct(string $value) | |
{ | |
$this->value = $value; | |
} | |
private static function constant(string $value): self | |
{ | |
return self::$instances[$value] ?? self::$instances[$value] = new self($value); | |
} | |
public static function fromString(string $value): self | |
{ | |
return self::constant($value); | |
} | |
public function toString(): string | |
{ | |
return $this->value; | |
} | |
public function __toString(): string | |
{ | |
return $this->toString(); | |
} | |
public function jsonSerialize(): string | |
{ | |
return $this->value; | |
} | |
public function __clone() | |
{ | |
throw new \RuntimeException('Cloning not supported'); | |
} | |
public function __sleep() | |
{ | |
throw new \RuntimeException('Serialization not supported'); | |
} | |
public function __wakeup() | |
{ | |
throw new \RuntimeException('Deserialization not supported'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment