Laravel Event Projector Released

Published on by

Laravel Event Projector Released image

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.

Paul Redmond photo

Staff writer at Laravel News. Full stack web developer and author.

Filed in:
Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
Paragraph

Manage your Laravel app as if it was a CMS – edit any text on any page or in any email without touching Blade or language files.

Visit Paragraph
Laravel Forge logo

Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Forge
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $7500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $2500/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
LoadForge logo

LoadForge

Easy, affordable load testing and stress tests for websites, APIs and databases.

LoadForge
Paragraph logo

Paragraph

Manage your Laravel app as if it was a CMS – edit any text on any page or in any email without touching Blade or language files.

Paragraph
Lucky Media logo

Lucky Media

Bespoke software solutions built for your business. We ♥ Laravel

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
DocuWriter.ai logo

DocuWriter.ai

Save hours of manually writing Code Documentation, Comments & DocBlocks, Test suites and Refactoring.

DocuWriter.ai
Rector logo

Rector

Your partner for seamless Laravel upgrades, cutting costs, and accelerating innovation for successful companies

Rector

The latest

View all →
Launch your Startup Fast with LaraFast image

Launch your Startup Fast with LaraFast

Read article
Embed Livewire Components on Any Website image

Embed Livewire Components on Any Website

Read article
Statamic announces next Flat Camp retreat (EU edition) image

Statamic announces next Flat Camp retreat (EU edition)

Read article
Laravel Herd releases v1.5.0 with new services. No more Docker, DBNGIN, or even homebrew! image

Laravel Herd releases v1.5.0 with new services. No more Docker, DBNGIN, or even homebrew!

Read article
Resources for Getting Up To Speed with Laravel 11 image

Resources for Getting Up To Speed with Laravel 11

Read article
Laravel 11 is now released! image

Laravel 11 is now released!

Read article