1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Domain\Aggregates; |
4
|
|
|
|
5
|
|
|
use Domain\Eventing\DomainEvent; |
6
|
|
|
use Domain\Eventing\UncommittedEvents; |
7
|
|
|
|
8
|
|
|
/** |
9
|
|
|
* Sane default Behaviour and state for the RecordsEvents interface |
10
|
|
|
* |
11
|
|
|
* @author Sebastiaan Hilbers <[email protected]> |
12
|
|
|
*/ |
13
|
|
|
trait EventSourced |
14
|
|
|
{ |
15
|
|
|
/** |
16
|
|
|
* Collection of events that are not persisted yet |
17
|
|
|
* @var UncommittedEvents |
18
|
|
|
*/ |
19
|
|
|
private $uncommittedEvents; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* Determine whether the object's state has changed since the last clearChanges(); |
23
|
|
|
* |
24
|
|
|
* @return bool |
25
|
|
|
*/ |
26
|
|
|
public function hasChanges() |
27
|
|
|
{ |
28
|
|
|
return !empty($this->uncommittedEvents); |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* Get all changes to the object since the last the last clearChanges(); |
33
|
|
|
* |
34
|
|
|
* @return UncommittedEvents |
35
|
|
|
*/ |
36
|
|
|
public function getChanges() |
37
|
|
|
{ |
38
|
|
|
return $this->uncommittedEvents; |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* Clear all state changes from this object. |
43
|
|
|
* |
44
|
|
|
* @return static |
45
|
|
|
*/ |
46
|
|
|
public function clearChanges() |
47
|
|
|
{ |
48
|
|
|
$this->uncommittedEvents = new UncommittedEvents($this->getIdentity()); |
49
|
|
|
|
50
|
|
|
return $this; |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
/** |
54
|
|
|
* Register a event happening on the aggregate |
55
|
|
|
* |
56
|
|
|
* @param DomainEvent $event |
57
|
|
|
* @return static |
58
|
|
|
*/ |
59
|
|
|
public function recordThat(DomainEvent $event) |
60
|
|
|
{ |
61
|
|
|
$this->bumpVersion(); |
62
|
|
|
|
63
|
|
|
if (is_null($this->uncommittedEvents)) { |
64
|
|
|
$this->uncommittedEvents = new UncommittedEvents($this->getIdentity()); |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
$this->uncommittedEvents->append($event); |
68
|
|
|
$this->when($event); |
69
|
|
|
|
70
|
|
|
return $this; |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
abstract protected function bumpVersion(); |
74
|
|
|
|
75
|
|
|
/** |
76
|
|
|
* The concrete class should have this method |
77
|
|
|
*/ |
78
|
|
|
abstract protected function when(DomainEvent $event); |
79
|
|
|
|
80
|
|
|
/** |
81
|
|
|
* The concrete class should have this method |
82
|
|
|
*/ |
83
|
|
|
abstract protected function getIdentity(); |
84
|
|
|
} |
85
|
|
|
|