|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace SmoothPhp\EventSourcing; |
|
4
|
|
|
|
|
5
|
|
|
use SmoothPhp\Contracts\EventBus\EventBus; |
|
6
|
|
|
use SmoothPhp\Contracts\EventSourcing\AggregateRoot as AggregateRootInterface; |
|
7
|
|
|
use SmoothPhp\Contracts\EventStore\EventStore; |
|
8
|
|
|
|
|
9
|
|
|
/** |
|
10
|
|
|
* Class EventSourcedRepository |
|
11
|
|
|
* @package SmoothPhp\EventSourcing |
|
12
|
|
|
* @author Simon Bennett <[email protected]> |
|
13
|
|
|
*/ |
|
14
|
|
|
abstract class EventSourcedRepository |
|
15
|
|
|
{ |
|
16
|
|
|
/** @var EventStore */ |
|
17
|
|
|
private $eventStore; |
|
18
|
|
|
|
|
19
|
|
|
/** @var EventBus */ |
|
20
|
|
|
private $eventBus; |
|
21
|
|
|
|
|
22
|
|
|
/** |
|
23
|
|
|
* EventSourcedRepository constructor. |
|
24
|
|
|
* @param EventStore $eventStore |
|
25
|
|
|
* @param EventBus $eventBus |
|
26
|
|
|
*/ |
|
27
|
|
|
public function __construct(EventStore $eventStore, EventBus $eventBus) |
|
28
|
|
|
{ |
|
29
|
|
|
$this->eventStore = $eventStore; |
|
30
|
|
|
$this->eventBus = $eventBus; |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
|
|
/** |
|
34
|
|
|
* @return string |
|
35
|
|
|
*/ |
|
36
|
|
|
abstract protected function getPrefix(); |
|
37
|
|
|
|
|
38
|
|
|
/** |
|
39
|
|
|
* @return string |
|
40
|
|
|
*/ |
|
41
|
|
|
abstract protected function getAggregateType(); |
|
42
|
|
|
|
|
43
|
|
|
/** |
|
44
|
|
|
* @param string $id |
|
45
|
|
|
* @return AggregateRootInterface |
|
46
|
|
|
* @throws \SmoothPhp\EventStore\EventStreamNotFound |
|
47
|
|
|
*/ |
|
48
|
|
|
public function load($id) |
|
49
|
|
|
{ |
|
50
|
|
|
$domainEvents = $this->eventStore->load($this->getPrefix() . $id); |
|
51
|
|
|
$aggregateClassName = $this->getAggregateType(); |
|
52
|
|
|
|
|
53
|
|
|
$aggregate = unserialize(sprintf('O:%d:"%s":0:{}', strlen($aggregateClassName), $aggregateClassName)); |
|
54
|
|
|
$aggregate->initializeState($domainEvents); |
|
55
|
|
|
|
|
56
|
|
|
return $aggregate; |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
|
|
/** |
|
60
|
|
|
* @param AggregateRootInterface $aggregate |
|
61
|
|
|
* @return void |
|
62
|
|
|
*/ |
|
63
|
|
|
public function save(AggregateRootInterface $aggregate) |
|
64
|
|
|
{ |
|
65
|
|
|
$events = $aggregate->getUncommittedEvents(); |
|
66
|
|
|
|
|
67
|
|
|
$this->eventStore->append($aggregate->getAggregateRootId(), $events); |
|
68
|
|
|
|
|
69
|
|
|
$this->eventBus->publish($events); |
|
70
|
|
|
} |
|
71
|
|
|
|
|
72
|
|
|
} |