1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\EventProjector; |
4
|
|
|
|
5
|
|
|
use Illuminate\Support\Str; |
6
|
|
|
use Spatie\EventProjector\Models\StoredEvent; |
7
|
|
|
|
8
|
|
|
abstract class AggregateRoot |
9
|
|
|
{ |
10
|
|
|
/** @var string */ |
11
|
|
|
private $aggregateUuid; |
12
|
|
|
|
13
|
|
|
/** @var array */ |
14
|
|
|
private $recordedEvents = []; |
15
|
|
|
|
16
|
|
|
public static function retrieve(string $uuid): AggregateRoot |
17
|
|
|
{ |
18
|
|
|
$aggregateRoot = (new static()); |
19
|
|
|
|
20
|
|
|
$aggregateRoot->aggregateUuid = $uuid; |
21
|
|
|
|
22
|
|
|
return $aggregateRoot->reconstituteFromEvents(); |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
public function recordThat(ShouldBeStored $domainEvent): AggregateRoot |
26
|
|
|
{ |
27
|
|
|
$this->recordedEvents[] = $domainEvent; |
28
|
|
|
|
29
|
|
|
$this->apply($domainEvent); |
30
|
|
|
|
31
|
|
|
return $this; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
public function persist(): AggregateRoot |
35
|
|
|
{ |
36
|
|
|
call_user_func( |
37
|
|
|
[$this->getStoredEventModel(), 'storeMany'], |
38
|
|
|
$this->getAndClearRecoredEvents(), |
39
|
|
|
$this->aggregateUuid |
40
|
|
|
); |
41
|
|
|
|
42
|
|
|
return $this; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
protected function getStoredEventModel(): string |
46
|
|
|
{ |
47
|
|
|
return $this->storedEventModel ?? config('event-projector.stored_event_model'); |
|
|
|
|
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
private function getAndClearRecoredEvents(): array |
51
|
|
|
{ |
52
|
|
|
$recordedEvents = $this->recordedEvents; |
53
|
|
|
|
54
|
|
|
$this->recordedEvents = []; |
55
|
|
|
|
56
|
|
|
return $recordedEvents; |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
private function reconstituteFromEvents(): AggregateRoot |
60
|
|
|
{ |
61
|
|
|
$this->getStoredEventModel()::uuid($this->aggregateUuid)->each(function (StoredEvent $storedEvent) { |
|
|
|
|
62
|
|
|
$this->apply($storedEvent->event); |
63
|
|
|
}); |
64
|
|
|
|
65
|
|
|
return $this; |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
private function apply(ShouldBeStored $event): void |
69
|
|
|
{ |
70
|
|
|
$classBaseName = class_basename($event); |
71
|
|
|
|
72
|
|
|
$camelCasedBaseName = ucfirst(Str::camel($classBaseName)); |
73
|
|
|
|
74
|
|
|
$applyingMethodName = "apply{$camelCasedBaseName}"; |
75
|
|
|
|
76
|
|
|
if (method_exists($this, $applyingMethodName)) { |
77
|
|
|
$this->$applyingMethodName($event); |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: