Created
October 1, 2018 11:20
-
-
Save macghriogair/ec30a876f4ec5e8a0301bd47453645b1 to your computer and use it in GitHub Desktop.
[Immutable] #valueobject #immutable
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 | |
| namespace Website\Traits; | |
| trait ImmutableTrait | |
| { | |
| /** @var bool */ | |
| private $constructorWasCalled = false; | |
| /** | |
| * ImmutableTrait constructor. | |
| * @throws \Exception | |
| */ | |
| public function __construct() | |
| { | |
| if (true === $this->constructorWasCalled) { | |
| $this->throwImmutableException(); | |
| } | |
| $this->constructorWasCalled = true; | |
| } | |
| /** | |
| * @param $name | |
| * @param $value | |
| * @throws \Exception | |
| */ | |
| final public function __set($name, $value) | |
| { | |
| $this->throwImmutableException(); | |
| } | |
| /** | |
| * @throws \Exception | |
| */ | |
| final public function __clone() | |
| { | |
| $this->throwImmutableException(); | |
| } | |
| /** | |
| * @return void | |
| * @throws \Exception | |
| */ | |
| final private function throwImmutableException() | |
| { | |
| throw new \Exception("The object is immutable."); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment