Skip to content

feat: add dynamic weight #506

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jun 16, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,45 @@ In a local environment, where events have a very low chance of getting fired con

## Tweaking projector order

You can add a weight property to a projector to tweak the order projectors are run in. Projectors with a lower weight run first. When no explicit weight is provided, the weight is considered `0`.
You can add a getWeight method to a projector to tweak the order projectors are run in. Projectors with a lower weight run first. When no explicit weight is provided, the weight is considered `0`.

```php
namespace App\Projectors;

use Spatie\EventSourcing\EventHandlers\Projectors\Projector;
use Spatie\EventSourcing\StoredEvents\StoredEvent;

class MyProjector extends Projector
{
public int $weight = 5;
public function getWeight(?StoredEvent $event): int
{
return 5;
}

//
}
```

Alternatively, you can determine the weight dynamically based on the event being processed. This allows you to prioritize certain events over others. The `$event` parameter will be `null` when the `resetState()` method is called (during projector reset operations).

```php
namespace App\Projectors;

use App\Events\MoneyAddedEvent;
use App\Events\MoneySubtractedEvent;
use Spatie\EventSourcing\EventHandlers\Projectors\Projector;
use Spatie\EventSourcing\StoredEvents\StoredEvent;

class MyProjector extends Projector
{
public function getWeight(?StoredEvent $event): int
{
return match ($event?->event_class) {
MoneyAddedEvent::class => 2,
MoneySubtractedEvent::class => -2,
default => 0,
};
}

//
}
Expand Down
35 changes: 32 additions & 3 deletions docs/using-reactors/creating-and-configuring-reactors.md
Original file line number Diff line number Diff line change
Expand Up @@ -185,14 +185,43 @@ class SendMoneyAddedMail

## Tweaking reactor order

You can add a weight property to a reactor to tweak the order reactors are run in. Reactors with a lower weight run first. When no explicit weight is provided, the weight is considered `0`.
You can add a getWeight method to a reactor to tweak the order reactors are run in. Reactors with a lower weight run first. When no explicit weight is provided, the weight is considered `0`.

```php
namespace App\Reactors;

class MyReactor
use Spatie\EventSourcing\EventHandlers\Reactors\Reactor;
use Spatie\EventSourcing\StoredEvents\StoredEvent;

class MyReactor extends Reactor
{
public int $weight = 5;
public function getWeight(?StoredEvent $event): int
{
return 5;
}
}
```

Alternatively, you can determine the weight dynamically based on the event being processed. This allows you to prioritize certain events over others.

```php
namespace App\Reactors;

use App\Events\MoneyAddedEvent;
use App\Events\MoneySubtractedEvent;
use Spatie\EventSourcing\EventHandlers\Reactors\Reactor;
use Spatie\EventSourcing\StoredEvents\StoredEvent;

class MyReactor extends Reactor
{
public function getWeight(?StoredEvent $event): int
{
return match ($event?->event_class) {
MoneyAddedEvent::class => 2,
MoneySubtractedEvent::class => -2,
default => 0,
};
}
}
```

Expand Down
2 changes: 2 additions & 0 deletions src/EventHandlers/EventHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,6 @@ public function handle(StoredEvent $storedEvent): void;
public function handleException(Exception $exception): void;

public function getEventHandlingMethods(): Collection;

public function getWeight(?StoredEvent $event): int;
}
8 changes: 4 additions & 4 deletions src/EventHandlers/EventHandlerCollection.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,25 +51,25 @@ public function remove(array $eventHandlerClassNames): void
->toArray();
}

public function syncEventHandlers(): self
public function syncEventHandlers(StoredEvent $event): self
{
return $this
->reject(
fn (EventHandler $eventHandler) => $eventHandler instanceof ShouldQueue
)
->sortBy(
fn (EventHandler $eventHandler) => $eventHandler->weight ?? 0
fn (EventHandler $eventHandler) => $eventHandler->getWeight($event)
);
}

public function asyncEventHandlers(): self
public function asyncEventHandlers(StoredEvent $event): self
{
return $this
->filter(
fn (EventHandler $eventHandler) => $eventHandler instanceof ShouldQueue
)
->sortBy(
fn (EventHandler $eventHandler) => $eventHandler->weight ?? 0
fn (EventHandler $eventHandler) => $eventHandler->getWeight($event)
);
}
}
5 changes: 5 additions & 0 deletions src/EventHandlers/HandlesEvents.php
Original file line number Diff line number Diff line change
Expand Up @@ -56,4 +56,9 @@ public function getEventHandlingMethods(): Collection
})
->map(fn (Collection $group) => $group->map(fn (Method $method) => $method->getName())->all());
}

public function getWeight(?StoredEvent $event): int
{
return $this->weight ?? 0;
}
}
24 changes: 12 additions & 12 deletions src/Projectionist.php
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ public function getAsyncProjectorsFor(StoredEvent $storedEvent): Collection
{
return $this->projectors
->forEvent($storedEvent)
->asyncEventHandlers();
->asyncEventHandlers($storedEvent);
}

public function addReactor($reactor): Projectionist
Expand Down Expand Up @@ -221,7 +221,7 @@ public function handle(StoredEvent $storedEvent): void
{
$projectors = $this->projectors
->forEvent($storedEvent)
->asyncEventHandlers();
->asyncEventHandlers($storedEvent);

$this->applyStoredEventToProjectors(
$storedEvent,
Expand All @@ -230,7 +230,7 @@ public function handle(StoredEvent $storedEvent): void

$reactors = $this->reactors
->forEvent($storedEvent)
->asyncEventHandlers();
->asyncEventHandlers($storedEvent);

$this->applyStoredEventToReactors(
$storedEvent,
Expand All @@ -242,13 +242,13 @@ public function handleWithSyncEventHandlers(StoredEvent $storedEvent): void
{
$projectors = $this->projectors
->forEvent($storedEvent)
->syncEventHandlers();
->syncEventHandlers($storedEvent);

$this->applyStoredEventToProjectors($storedEvent, $projectors);

$reactors = $this->reactors
->forEvent($storedEvent)
->syncEventHandlers();
->syncEventHandlers($storedEvent);

$this->applyStoredEventToReactors($storedEvent, $reactors);
}
Expand All @@ -262,18 +262,18 @@ private function applyStoredEventToProjectors(StoredEvent $storedEvent, Collecti
{
$this->isProjecting = true;

foreach ($projectors as $projector) {
$this->callEventHandler($projector, $storedEvent);
}
$projectors
->sortBy(fn (EventHandler $eventHandler) => $eventHandler->getWeight($storedEvent))
->each(fn (EventHandler $projector) => $this->callEventHandler($projector, $storedEvent));

$this->isProjecting = false;
}

private function applyStoredEventToReactors(StoredEvent $storedEvent, Collection $reactors): void
{
foreach ($reactors as $reactor) {
$this->callEventHandler($reactor, $storedEvent);
}
$reactors
->sortBy(fn (EventHandler $eventHandler) => $eventHandler->getWeight($storedEvent))
->each(fn (EventHandler $reactor) => $this->callEventHandler($reactor, $storedEvent));
}

private function callEventHandler(EventHandler $eventHandler, StoredEvent $storedEvent): bool
Expand Down Expand Up @@ -323,7 +323,7 @@ public function replay(
?string $aggregateUuid = null
): void {
$projectors = (new EventHandlerCollection($projectors))
->sortBy(fn (EventHandler $eventHandler) => $eventHandler->weight ?? 0);
->sortBy(fn (EventHandler $eventHandler) => $eventHandler->getWeight(null));

$this->isReplaying = true;

Expand Down
2 changes: 1 addition & 1 deletion src/StoredEvents/StoredEvent.php
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ protected function shouldDispatchJob(): bool
/** @var \Spatie\EventSourcing\EventHandlers\EventHandlerCollection $eventHandlers */
$eventHandlers = Projectionist::allEventHandlers();

return $eventHandlers->forEvent($this)->asyncEventHandlers()->isNotEmpty();
return $eventHandlers->forEvent($this)->asyncEventHandlers($this)->isNotEmpty();
}

protected function instantiateEvent(?ShouldBeStored $originalEvent): void
Expand Down
43 changes: 33 additions & 10 deletions tests/ProjectionistTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use Illuminate\Contracts\Container\BindingResolutionException;
use Illuminate\Support\Facades\Queue;

use Spatie\EventSourcing\Tests\TestClasses\Projectors\ProjectorWithDynamicWeight;
use function PHPUnit\Framework\assertCount;
use function PHPUnit\Framework\assertEquals;
use function PHPUnit\Framework\assertInstanceOf;
Expand Down Expand Up @@ -66,30 +67,42 @@
assertEquals(1, ProjectorThatThrowsAnException::$exceptionsHandled);
});

it('will call projectors ordered by weight', function () {
it('will call projectors ordered by weight', function (string $eventClass, array $sortedProjectors) {
app()->singleton(ProjectorWithWeightTestHelper::class);

Projectionist::addProjector(ProjectorWithDynamicWeight::class);
Projectionist::addProjector(ProjectorWithHighWeight::class);
Projectionist::addProjector(ProjectorWithoutWeight::class);
Projectionist::addProjector(ProjectorWithNegativeWeight::class);
Projectionist::addProjector(ProjectorWithLowWeight::class);

event(new MoneyAddedEvent($this->account, 1000));
event(new $eventClass($this->account, 1000));

assertSame([
assertSame($sortedProjectors, app(ProjectorWithWeightTestHelper::class)->calledBy);
})->with([
[MoneyAddedEvent::class, [
ProjectorWithNegativeWeight::class,
ProjectorWithoutWeight::class,
ProjectorWithLowWeight::class,
ProjectorWithDynamicWeight::class,
ProjectorWithHighWeight::class,
], app(ProjectorWithWeightTestHelper::class)->calledBy);
});
]],
[MoneySubtractedEvent::class, [
ProjectorWithNegativeWeight::class,
ProjectorWithDynamicWeight::class,
ProjectorWithoutWeight::class,
ProjectorWithLowWeight::class,
ProjectorWithHighWeight::class,
]],
]);

it('will replay projectors ordered by weight', function () {
it('will replay projectors ordered by weight', function (string $eventClass, array $sortedProjectors) {
app()->singleton(ProjectorWithWeightTestHelper::class);

event(new MoneyAddedEvent($this->account, 1000));
event(new $eventClass($this->account, 1000));

Projectionist::addProjectors([
ProjectorWithDynamicWeight::class,
ProjectorWithHighWeight::class,
ProjectorWithoutWeight::class,
ProjectorWithNegativeWeight::class,
Expand All @@ -98,13 +111,23 @@

Projectionist::replay(Projectionist::getProjectors());

assertSame([
assertSame($sortedProjectors, app(ProjectorWithWeightTestHelper::class)->calledBy);
})->with([
[MoneyAddedEvent::class, [
ProjectorWithNegativeWeight::class,
ProjectorWithoutWeight::class,
ProjectorWithLowWeight::class,
ProjectorWithDynamicWeight::class,
ProjectorWithHighWeight::class,
], app(ProjectorWithWeightTestHelper::class)->calledBy);
});
]],
[MoneySubtractedEvent::class, [
ProjectorWithNegativeWeight::class,
ProjectorWithDynamicWeight::class,
ProjectorWithoutWeight::class,
ProjectorWithLowWeight::class,
ProjectorWithHighWeight::class,
]],
]);

it('can catch exceptions and still continue calling other projectors', function () {
$this->setConfig('event-sourcing.catch_exceptions', true);
Expand Down
36 changes: 36 additions & 0 deletions tests/TestClasses/Projectors/ProjectorWithDynamicWeight.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php

namespace Spatie\EventSourcing\Tests\TestClasses\Projectors;

use Spatie\EventSourcing\EventHandlers\Projectors\Projector;
use Spatie\EventSourcing\StoredEvents\StoredEvent;
use Spatie\EventSourcing\Tests\TestClasses\Events\MoneyAddedEvent;
use Spatie\EventSourcing\Tests\TestClasses\Events\MoneySubtractedEvent;
use Spatie\EventSourcing\Tests\TestClasses\ProjectorWithWeightTestHelper;

class ProjectorWithDynamicWeight extends Projector
{
public function __construct(
private ProjectorWithWeightTestHelper $projectorWithWeightTestHelper,
) {
}

public function getWeight(?StoredEvent $event): int
{
return match ($event?->event_class) {
MoneyAddedEvent::class => 2,
MoneySubtractedEvent::class => -2,
default => 0,
};
}

public function onMoneyAdded(MoneyAddedEvent $event): void
{
$this->projectorWithWeightTestHelper->calledBy(static::class);
}

public function onMoneySubtracted(MoneySubtractedEvent $event): void
{
$this->projectorWithWeightTestHelper->calledBy(static::class);
}
}
6 changes: 6 additions & 0 deletions tests/TestClasses/Projectors/ProjectorWithHighWeight.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Spatie\EventSourcing\EventHandlers\Projectors\Projector;
use Spatie\EventSourcing\Tests\TestClasses\Events\MoneyAddedEvent;
use Spatie\EventSourcing\Tests\TestClasses\Events\MoneySubtractedEvent;
use Spatie\EventSourcing\Tests\TestClasses\ProjectorWithWeightTestHelper;

class ProjectorWithHighWeight extends Projector
Expand All @@ -19,4 +20,9 @@ public function onMoneyAdded(MoneyAddedEvent $event): void
{
$this->projectorWithWeightTestHelper->calledBy(static::class);
}

public function onMoneySubtracted(MoneySubtractedEvent $event): void
{
$this->projectorWithWeightTestHelper->calledBy(static::class);
}
}
6 changes: 6 additions & 0 deletions tests/TestClasses/Projectors/ProjectorWithLowWeight.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Spatie\EventSourcing\EventHandlers\Projectors\Projector;
use Spatie\EventSourcing\Tests\TestClasses\Events\MoneyAddedEvent;
use Spatie\EventSourcing\Tests\TestClasses\Events\MoneySubtractedEvent;
use Spatie\EventSourcing\Tests\TestClasses\ProjectorWithWeightTestHelper;

class ProjectorWithLowWeight extends Projector
Expand All @@ -19,4 +20,9 @@ public function onMoneyAdded(MoneyAddedEvent $event): void
{
$this->projectorWithWeightTestHelper->calledBy(static::class);
}

public function onMoneySubtracted(MoneySubtractedEvent $event): void
{
$this->projectorWithWeightTestHelper->calledBy(static::class);
}
}
Loading