Skip to content

Instantly share code, notes, and snippets.

@bwaidelich

bwaidelich/Customer.php

Last active Jul 29, 2020
Embed
What would you like to do?
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
You can’t perform that action at this time.