Skip to content

Instantly share code, notes, and snippets.

@JasonTheAdams
Last active October 10, 2019 17:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save JasonTheAdams/584efb0350af3bf6e5ab7cbd12eb449d to your computer and use it in GitHub Desktop.
Save JasonTheAdams/584efb0350af3bf6e5ab7cbd12eb449d to your computer and use it in GitHub Desktop.
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 $comparison === $this->value;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment