-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEventSourcedRepository.php
90 lines (74 loc) · 2.23 KB
/
EventSourcedRepository.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
<?php
namespace SmoothPhp\EventSourcing;
use SmoothPhp\Contracts\EventBus\EventBus;
use SmoothPhp\Contracts\EventSourcing\AggregateRoot as AggregateRootInterface;
use SmoothPhp\Contracts\EventStore\EventStore;
/**
* Class EventSourcedRepository
* @package SmoothPhp\EventSourcing
* @author Simon Bennett <[email protected]>
*/
abstract class EventSourcedRepository
{
/** @var EventStore */
private $eventStore;
/** @var EventBus */
private $eventBus;
/**
* EventSourcedRepository constructor.
* @param EventStore $eventStore
* @param EventBus $eventBus
*/
public function __construct(EventStore $eventStore, EventBus $eventBus)
{
$this->eventStore = $eventStore;
$this->eventBus = $eventBus;
}
/**
* @return string
*/
abstract protected function getPrefix();
/**
* @return string
*/
abstract protected function getAggregateType();
/**
* @param string $id
* @return AggregateRootInterface
* @throws \SmoothPhp\EventStore\EventStreamNotFound
*/
public function load($id)
{
$domainEvents = $this->eventStore->load($this->getPrefix() . $id);
$aggregateClassName = $this->getAggregateType();
$aggregate = unserialize(sprintf( 'O:%d:"%s":0:{}',strlen($aggregateClassName), $aggregateClassName));
$aggregate->initializeState($domainEvents);
return $aggregate;
}
/**
* @param AggregateRootInterface $aggregate
* @return void
*/
public function save(AggregateRootInterface $aggregate)
{
$this->saveAggregate($aggregate,false);
}
/**
* @param AggregateRootInterface $aggregate
* @return void
*/
public function saveWithoutPlayheadCheck(AggregateRootInterface $aggregate)
{
$this->saveAggregate($aggregate,true);
}
/**
* @param AggregateRootInterface $aggregate
* @param bool $ignorePlayhead
*/
private function saveAggregate(AggregateRootInterface $aggregate,bool $ignorePlayhead = false)
{
$events = $aggregate->getUncommittedEvents();
$this->eventStore->append($aggregate->getAggregateRootId(), $events,$ignorePlayhead);
$this->eventBus->publish($events);
}
}