This repository has been archived by the owner on Feb 21, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathexample1.php
95 lines (78 loc) · 2.6 KB
/
example1.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
91
92
93
94
<?php
/**
* This example shows the implementation for a "change email"
* command on a User entity. The command accepts a user id
* and a new email address. The change is delegated to the
* user object where the "DomainObjectChanged" event is raised.
*
* A listener picks up this event and displays the changed e-mail.
*/
namespace MyApp;
require_once __DIR__ . "/../vendor/autoload.php";
use LiteCQRS\DomainEventProvider;
use LiteCQRS\Bus\DirectCommandBus;
use LiteCQRS\Bus\InMemoryEventMessageBus;
use LiteCQRS\Bus\IdentityMap\SimpleIdentityMap;
use LiteCQRS\Bus\IdentityMap\EventProviderQueue;
use LiteCQRS\Bus\EventMessageHandlerFactory;
use LiteCQRS\DefaultCommand;
use LiteCQRS\DomainObjectChanged;
class User extends DomainEventProvider
{
private $email = "[email protected]";
public function changeEmail($email)
{
$this->raise(new DomainObjectChanged("ChangeEmail", array("email" => $email, "oldEmail" => $this->email)));
$this->email = $email;
}
}
class ChangeEmailCommand extends DefaultCommand
{
public $id;
public $email;
}
class UserService
{
private $map;
private $users;
public function __construct(SimpleIdentityMap $map)
{
$this->map = $map;
}
public function changeEmail(ChangeEmailCommand $command)
{
$user = $this->findUserById($command->id);
$user->changeEmail($command->email);
}
private function findUserById($id)
{
if (!isset($this->users[$id])) {
// here would normally be a database call or something
$this->users[$id] = new User();
$this->map->add($this->users[$id]);
}
return $this->users[$id];
}
}
class MyEventHandler
{
public function onChangeEmail(DomainObjectChanged $event)
{
echo "E-Mail changed from " . $event->oldEmail . " to " . $event->email . "\n";
}
}
// 1. Setup the Library with InMemory Handlers
$messageBus = new InMemoryEventMessageBus();
$identityMap = new SimpleIdentityMap();
$queue = new EventProviderQueue($identityMap);
$commandBus = new DirectCommandBus(array(
new EventMessageHandlerFactory($messageBus, $queue)
));
// 2. Register a command service and an event handler
$userService = new UserService($identityMap);
$someEventHandler = new MyEventHandler();
$commandBus->register('MyApp\ChangeEmailCommand', $userService);
$messageBus->register($someEventHandler);
// 3. Invoke command!
$commandBus->handle(new ChangeEmailCommand(array('id' => 1234, 'email' => '[email protected]')));
$commandBus->handle(new ChangeEmailCommand(array('id' => 1234, 'email' => '[email protected]')));