Skip to content

Conversation

@nick-potts
Copy link
Contributor

@nick-potts nick-potts commented Nov 27, 2024

  1. New DeferBy Attribute:
#[DeferBy(property_names: string|array|null, name: string = 'EventClassName', replay_only: bool = false)]
  1. New Verbs::defer() method:
Verbs::defer(State|string|iterable|null $unique_by, callable $callback, string $name = 'Default')

Key Benefits:

  • Prevents duplicate operations by ensuring expensive operations only run once
  • Operations are deferred until after everything is committed
  • Can be scoped by state, property, or custom name

Examples of Usage:

  1. Property-based uniqueness:
class UserPasswordUpdated extends Event 
{
    #[StateId(UserState::class)] 
    public int $user_id;

    #[DeferBy('user_id')]
    public function handle(UserState $user): void 
    {
        // Only the latest password is written
        $user->write();
    }
}
  1. Named uniqueness:
class OrderCreated extends Event 
{
    #[DeferBy(null, name: 'daily_report')]
    public function handle(): void 
    {
        // Will only run once even if multiple orders are processed
        $this->generateDailyReports();
    }
}
  1. Programmatic unique operations:
// Only runs once after commit
Verbs::defer($state, function() {
    $this->rebuildCache();
});

This is particularly useful for optimizing performance in scenarios where multiple events might trigger the same expensive operation, but running it once at the end is sufficient.

@nick-potts nick-potts marked this pull request as draft December 3, 2024 02:35
@nick-potts nick-potts changed the title WIP: Deferred writes during replays WIP: Deferred unique writes Dec 3, 2024
@nick-potts nick-potts marked this pull request as ready for review December 3, 2024 03:16
public function __construct(
public string|array|null $property_name,
public string $name = self::EVENT_CLASS,
public bool $replay_only = false,
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Potentially this should default to true. Event::commit() will default to returning values, and only replays will benefit initially.

@nick-potts nick-potts changed the title WIP: Deferred unique writes Deferred unique writes Feb 16, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant