Laravel Event Projector Released
Published on by Paul Redmond
Freek Van der Herten and the Spatie crew have been working on Laravel Event Projector, a package for event sourcing in Laravel. The first stable version (v1.0.0) is now live!
You can install Event Projector in your project with composer, and thanks to Laravel’s package auto-discovery, you’re ready to go after you publish the package’s migrations and configuration!
composer require spatie/laravel-event-projector:^1.0.0
Event Project requires PHP 7.2, so your app will need to support the latest version of PHP, versus the Laravel constraint of PHP >=7.1.3
.
What is Event Sourcing
According to Event Sourcing Pattern, an overview of event sourcing is as follows:
Instead of storing just the current state of the data in a domain, use an append-only store to record the full series of actions taken on that data. The store acts as the system of record and can be used to materialize the domain objects. This can simplify tasks in complex domains, by avoiding the need to synchronize the data model and the business domain, while improving performance, scalability, and responsiveness. It can also provide consistency for transactional data, and maintain full audit trails and history that can enable compensating actions.
I’d recommend reading the whole article, it provides an excellent overview and some ideas on when using this pattern is appropriate, and other situations where this pattern might not be useful.
I like Spatie’s explanation of Event Sourcing from the documentation’s introduction:
Event sourcing is to data what Git is to code. Most applications only have their current state stored in a database. A lot of useful information gets lost: you don’t know how the application got to this state.
Event sourcing tries to solve this problem by storing all events that happen in your app. The state of your application is built by listening to those events.
Here’s a traditional example to make it more clear. Imagine you’re a bank. Your clients have accounts. Storing the balance of the accounts wouldn’t be enough, all the transactions should be remembered too. With event sourcing, the balance isn’t a standalone database field, but a value calculated from the stored transactions. This is only one of the many benefits event sourcing brings to the table.
This package aims to be the simple and very pragmatic way to get started with event sourcing in Laravel.
It seems like Event Projector helps to make event sourcing simple and the documentation has helped me solidify how to use event sourcing using concepts in Laravel I am already familiar with.
Basic Event Sourcing in Laravel
To get familiar with event sourcing using the Event Projector package, you should check out Writing your first projector to get an idea of the pieces involved.
At a high level, (forgive me if I am not perfect in my assessment, event sourcing is a new concept for me) event sourcing with Event Projector involves:
- Eloquent models
- Events implementing the
ShouldBeStored
interface - Projector classes
From the documentation, here’s an example of a model class with the createWithAttributes
static method:
namespace App; use App\Events\AccountCreated;use App\Events\AccountDeleted;use App\Events\MoneyAdded;use App\Events\MoneySubtracted;use Illuminate\Database\Eloquent\Model;use Ramsey\Uuid\Uuid; class Account extends Model{ protected $guarded = []; protected $casts = [ 'broke_mail_send' => 'bool', ]; public static function createWithAttributes(array $attributes): Account { /* * Let's generate a uuid. */ $attributes['uuid'] = (string) Uuid::uuid4(); /* * The account will be created inside this event using the generated uuid. */ event(new AccountCreated($attributes)); /* * The uuid will be used the retrieve the created account. */ return static::uuid($attributes['uuid']); } public function addMoney(int $amount) { event(new MoneyAdded($this->uuid, $amount)); } public function subtractMoney(int $amount) { event(new MoneySubtracted($this->uuid, $amount)); } public function delete() { event(new AccountDeleted($this->uuid)); } /* * A helper method to quickly retrieve an account by uuid. */ public static function uuid(string $uuid): ?Account { return static::where('uuid', $uuid)->first(); }}
The thing to note here is the events being fired for AccountCreated
, MoneyAdded
, MoneySubtracted
, and AccountDeleted
.
Here’s an example of the MoneyAdded
event. The ShouldBeStored
interface that signifies to the Event Projector package that this event should be stored:
namespace App\Events; use Spatie\EventProjector\ShouldBeStored; class MoneyAdded implements ShouldBeStored{ /** @var string */ public $accountUuid; /** @var int */ public $amount; public function __construct(string $accountUuid, int $amount) { $this->accountUuid = $accountUuid; $this->amount = $amount; }}
Finally, here’s a partial example of an event handler inside of a projector class to add money to the account balance (that’s my favorite type of bank event):
public function onMoneyAdded(MoneyAdded $event){ $account = Account::uuid($event->accountUuid); $account->balance += $event->amount; $account->save();}
To tie it all together, here’s an example from the documentation of creating a new account and adding money:
Account::createWithAttributes(['name' => 'Luke']);Account::createWithAttributes(['name' => 'Leia']); $account = Account::where(['name' => 'Luke'])->first();$anotherAccount = Account::where(['name' => 'Leia'])->first(); $account->addMoney(1000);$anotherAccount->addMoney(500);$account->subtractMoney(50);
I imagine that Luke and Leia’s balances represent the Galactic Credit Standard, although, I am not entirely sure if they would be on the grid like this.
One section of this documentation stuck out to me as a benefit of using event sourcing via this package:
The cool thing about projectors is that you can write them after events have happened. Imagine that someone at the bank wants to have a report of the average balance of each account. You would be able to write a new projector, replay all events, and have that data.
The idea that you can write new projectors after events have happened seems powerful. It means that you don’t have to “get it all right” up front, and can iterate.
If you’re concerned about performance, the documentation claims that projects are “very fast to query.”
Learn More
I’d encourage you to read through the Event Projector Documentation to get started and make sure you have a fresh copy of PHP 7.2 available. Spatie also has a Demo Laravel Event Projector Application showcasing the Event Projector package that you probably want to check out.
You can download the code, star the repo, and contribute to Event Projector on the GitHub repo. At the time of writing, Event Projector is already up to 15 contributors leading up to the stable 1.0 release. Nice work Spatie! Event Projector looks like another excellent package for the Laravel community.