Event Sourcing

Handling Event Sourcing with ease

Introduction

For detailed information about the Event Sourcing pattern, click here

TL;DR:

  • Storing your Entity (eg Order) in a stream of Events, append-only.

  • Great source for:

    • Debugging production issues

    • Analytical reasons

Usage

Event Sourcing of ShipSaaS is utilizing Laravel's Event feature. So with a single Event::dispatch(...) will do the job.

EventSourcingContract

You need to create an Event class, indeed. And your Event class must implement the EventSourcingContract

Implements the required methods and that's it.

Required methodsReturn TypeDescription

getModel

Model (Eloquent)

The model that you want to record the event. Eg: Order

getUser

Model or null

The current logged in User that's interacting with the main Model.

getCategory

string

Category of the event, eg: services.order

getEventProperties

array

The related data of the Event that you want to store, eg for OrderCreated, I would store: - total_price - total_items - note - ...

Dispatch the Event

Use Laravel Event Facade or EventManager:

$event = new OrderCreated($order);

Event::dispatch($event);

After dispatched, you would see a new record in the events table. Check it out!

Queue

If you wish to run the record under Queue's stage, no worries. Update these settings:

  • saas-ready.php

    • event-sourcing.should-queue to true

    • event-sourcing.queue-name if you want to push it to a specific queue

      • default: will use the default queue name of the driver  

    • event-sourcing.queue-connection if you want to push it to a specific connection, eg redis

      • default: will use the default queue driver from env

Relationship for Event

If you want to use our default Event eloquent (and you should) and do the eager-loading, then you need to configure the user relationship for it, via:

  • saas-ready.php

    • event-sourcing.user-model eg App\Models\User

Alternatively, you can create a new Event model and extend our Event class, then override the user method.

Last updated