Last active
July 16, 2018 19:47
-
-
Save Great-Antique/5cb39963a9b225e04c33a94941c3b5ae to your computer and use it in GitHub Desktop.
Immutable object and CQS
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 SomeImmutableObject { | |
private $a; | |
private $b; | |
public function __construct($a, $b) { | |
$this->a = $a; | |
$this->b = $b; | |
} | |
public function withA($a) { | |
$cloned = clone $this; | |
$cloned->a = $a; | |
return $cloned; | |
} | |
} | |
class SomeClassThatWantToChangeAInImmutableObject { | |
private $eventDispatcher; | |
public function __construct($eventDispatcher) { | |
$this->eventDispatcher = $eventDispatcher; | |
} | |
public function someCommand($immutableObject, $a) { | |
$newImmutableObject = $immutableObject->withA($a); | |
$this->eventDispatcher->dispatch(new NewImmutableObjectWasCreated($newImmutableObject)); | |
} | |
} | |
class SomeClass { | |
private $eventListener; | |
private $someClassThatWantToChangeAInImmutableObject; | |
public function __construct($eventListener, $someClassThatWantToChangeAInImmutableObject) { | |
$this->eventListener = $eventListener; | |
$this->someClassThatWantToChangeAInImmutableObject = $someClassThatWantToChangeAInImmutableObject; | |
} | |
public function doSomethingWithImmutableObject($immutableObject) { | |
$thisNewImmutableObjectWillBeCreated = null; | |
$this->eventListener->addListener( | |
NewImmutableObjectWasCreated::class, | |
function ($event) use ($thisNewImmutableObjectWillBeCreated) { | |
$thisNewImmutableObjectWillBeCreated = $event->getNewImmutableObject(); | |
} | |
); | |
$this->someClassThatWantToChangeAInImmutableObject->someCommand($immutableObject, 555); | |
// Do something with "new immutable object" that has been created during "some command" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment