Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Enumeration example of the Object Value Design Pattern
<?php
class PostStatus
{
const PRIVATE = 'private';
const DRAFT = 'draft';
const PUBLISHED = 'published';
const TRASHED = 'trash';
/**
* @var string
*/
private $value;
public static function all()
{
return [
self::PRIVATE,
self::DRAFT,
self::PUBLISHED,
self::TRASHED
];
}
public function __construct($value)
{
if (! in_array($value, self::all())) {
throw new InvalidArgumentException("Invalid PostStatus value: {$value}");
}
$this->value = $value;
}
public function __toString()
{
return $this->value;
}
public function is($comparison)
{
if ($comparison instanceof self) {
return $comparison->value === $this->value;
} else {
return (string) $comparison === $this->value;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment