Last active
October 10, 2019 17:23
-
-
Save JasonTheAdams/584efb0350af3bf6e5ab7cbd12eb449d to your computer and use it in GitHub Desktop.
Enumeration example of the Object Value Design Pattern
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 | |
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