Skip to content

Instantly share code, notes, and snippets.

@dgafka
Last active December 22, 2021 19:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dgafka/5e608677bafe153c46464afc8f0656eb to your computer and use it in GitHub Desktop.
Save dgafka/5e608677bafe153c46464afc8f0656eb to your computer and use it in GitHub Desktop.
Event Sourcing PHP Example 06
<?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