-
-
Save salcode/d6fcfdb9105ca3b1942ff13e1dbdeffa to your computer and use it in GitHub Desktop.
Enumeration example of the Object Value Design Pattern
This file contains hidden or 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 (string) $comparison === $this->value; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment