public function postAction($id) { if (!$id) { // Normal PHP exception. throw new \Exception("No ID specified."); } $user = User::findById($id); $profile = Model\Profile::findByUser($user); if (!$user || !$profile) { throw new ModelException("No user or profile found."); } $comment = new Comment($user, $profile, "Hello!"); $comment->save(); if ($comment->getErrors()) { // Imported exception. throw new Exception("It failed."); } return $comment->getId(); }
} namespace { //Set up an EventStore with an InMemoryAdapter (Only useful for testing, persistent adapters for ProophEventStore are available) use My\Infrastructure\UserRepositoryImpl; use My\Model\User; use Prooph\Common\Event\ActionEvent; use Prooph\Common\Event\ProophActionEventEmitter; use Prooph\EventStore\Adapter\InMemoryAdapter; use Prooph\EventStore\EventStore; $eventStore = new EventStore(new InMemoryAdapter(), new ProophActionEventEmitter()); //Now we set up our user repository and inject the EventStore //Normally this should be done in an IoC-Container and the receiver of the repository should require My\Model\UserRepository $userRepository = new UserRepositoryImpl($eventStore); //Ok lets start a new transaction and create a user $eventStore->beginTransaction(); $user = User::nameNew('John Doe'); $userRepository->add($user); //Before we commit the transaction let's attach a listener to check that the UserWasCreated event is published after commit $eventStore->getActionEventEmitter()->attachListener('commit.post', function (ActionEvent $event) { foreach ($event->getParam('recordedEvents', new \ArrayIterator()) as $streamEvent) { echo sprintf("Event with name %s was recorded. It occurred on %s UTC /// ", $streamEvent->messageName(), $streamEvent->createdAt()->format('Y-m-d H:i:s')); } }); $eventStore->commit(); $userId = $user->userId(); unset($user); //Ok, great. Now let's see how we can grab the user from the repository and change the name //First we need to start a new transaction $eventStore->beginTransaction(); //The repository automatically tracks changes of the user... $loadedUser = $userRepository->get($userId);