Skip to content

Instantly share code, notes, and snippets.

@webdevilopers
Created July 20, 2020 08:56
Show Gist options
  • Save webdevilopers/e2b0d1de9d8f1a0e965b9eedda67d523 to your computer and use it in GitHub Desktop.
Save webdevilopers/e2b0d1de9d8f1a0e965b9eedda67d523 to your computer and use it in GitHub Desktop.
Prooph Event Store: Query event stream
<?php
final class Merger
{
// ...
private function getInitialEventFromStream(EmploymentContractId $contractId): EmploymentContractSigned
{
$query = $this->projectionManager->createQuery();
$query
->init(function (): array {
return [];
})
->fromStream('employment_contract_stream')
->when([
EmploymentContractSigned::class => function (
array $state, EmploymentContractSigned $event
) use ($contractId): array {
if ($event->contractId()->sameValueAs($contractId)) {
$state[] = $event;
$this->stop();
}
return $state;
}
])
->run();
return $query->getState()[0];
}
}
@webdevilopers
Copy link
Author

webdevilopers commented Jul 20, 2020

@fjogeleit
Copy link

A alternative with a Metadatamatcher

<?php

final class Merger
{
    // ...
    private function getInitialEventFromStream(EmploymentContractId $contractId): EmploymentContractSigned
    {
        $metadataMatcher = (new MetadataMatcher())
            ->withMetadataMatch('_aggregate_id', Operator::EQUALS(), $contractId->toString());

        $query = $this->projectionManager->createQuery();
        $query
            ->init(function (): array {
                return [];
            })
            ->fromStream('employment_contract_stream', $metadataMatcher)
            ->when([
                EmploymentContractSigned::class => function (
                    array $state, EmploymentContractSigned $event
                ): array {
                    $state[] = $event;

                    return $state;
                }
            ])
            ->run();

        return $query->getState()[0];
    }
}

@prolic
Copy link

prolic commented Jul 20, 2020

I think the alternative using a metadata matcher would result in better performance. Other than hand-written manual sql queries, this should be the best approach.

@webdevilopers
Copy link
Author

Worked like a charm @fjogeleit @prolic! Thank you for this.

@webdevilopers
Copy link
Author

webdevilopers commented Jul 26, 2020

Update fromStream for Projection, Query and ReadModelProjection:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment