Last active
December 22, 2021 19:26
-
-
Save dgafka/5e608677bafe153c46464afc8f0656eb to your computer and use it in GitHub Desktop.
Event Sourcing PHP Example 06
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
#[Projection("price_change_over_time", Product::class)] // 1 | |
class PriceChangeOverTimeProjection | |
{ | |
/** @var PriceChange[][] */ | |
private array $priceChangeOverTime = []; | |
/** | |
* @return PriceChange[] | |
*/ | |
#[QueryHandler("product.getPriceChange")] // 2 | |
public function getPriceChangesFor(int $productId): array | |
{ | |
if (!isset($this->priceChangeOverTime[$productId])) { | |
return []; | |
} | |
return $this->priceChangeOverTime[$productId]; | |
} | |
#[EventHandler] // 3 | |
public function registerPrice(ProductWasRegistered $event): void | |
{ | |
$this->priceChangeOverTime[$event->getProductId()][] = new PriceChange($event->getPrice(), 0); | |
} | |
#[EventHandler] | |
public function registerPriceChange(PriceWasChanged $event): void | |
{ | |
$lastPrice = end($this->priceChangeOverTime[$event->getProductId()]); | |
$this->priceChangeOverTime[$event->getProductId()][] = new PriceChange($event->getPrice(), $event->getPrice() - $lastPrice->getPrice()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment