Skip to content

Instantly share code, notes, and snippets.

@Great-Antique
Last active July 16, 2018 19:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Great-Antique/5cb39963a9b225e04c33a94941c3b5ae to your computer and use it in GitHub Desktop.
Save Great-Antique/5cb39963a9b225e04c33a94941c3b5ae to your computer and use it in GitHub Desktop.
Immutable object and CQS
<?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