Skip to content

Instantly share code, notes, and snippets.

@bwaidelich
Last active July 29, 2020 10:13
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 bwaidelich/ebc348200c859f0fa5b6c26330108337 to your computer and use it in GitHub Desktop.
Save bwaidelich/ebc348200c859f0fa5b6c26330108337 to your computer and use it in GitHub Desktop.
Serializable Value Object
<?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);
}
}
<?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