Laravel Event Projector Released


July 13th, 2018


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!

1composer 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:

1namespace App;
3use App\Events\AccountCreated;
4use App\Events\AccountDeleted;
5use App\Events\MoneyAdded;
6use App\Events\MoneySubtracted;
7use Illuminate\Database\Eloquent\Model;
8use Ramsey\Uuid\Uuid;
10class Account extends Model
12 protected $guarded = [];
14 protected $casts = [
15 'broke_mail_send' => 'bool',
16 ];
18 public static function createWithAttributes(array $attributes): Account
19 {
20 /*
21 * Let's generate a uuid.
22 */
23 $attributes['uuid'] = (string) Uuid::uuid4();
25 /*
26 * The account will be created inside this event using the generated uuid.
27 */
28 event(new AccountCreated($attributes));
30 /*
31 * The uuid will be used the retrieve the created account.
32 */
33 return static::uuid($attributes['uuid']);
34 }
36 public function addMoney(int $amount)
37 {
38 event(new MoneyAdded($this->uuid, $amount));
39 }
41 public function subtractMoney(int $amount)
42 {
43 event(new MoneySubtracted($this->uuid, $amount));
44 }
46 public function delete()
47 {
48 event(new AccountDeleted($this->uuid));
49 }
51 /*
52 * A helper method to quickly retrieve an account by uuid.
53 */
54 public static function uuid(string $uuid): ?Account
55 {
56 return static::where('uuid', $uuid)->first();
57 }

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:

1namespace App\Events;
3use Spatie\EventProjector\ShouldBeStored;
5class MoneyAdded implements ShouldBeStored
7 /** @var string */
8 public $accountUuid;
10 /** @var int */
11 public $amount;
13 public function __construct(string $accountUuid, int $amount)
14 {
15 $this->accountUuid = $accountUuid;
17 $this->amount = $amount;
18 }

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):

1public function onMoneyAdded(MoneyAdded $event)
3 $account = Account::uuid($event->accountUuid);
5 $account->balance += $event->amount;
7 $account->save();

To tie it all together, here’s an example from the documentation of creating a new account and adding money:

1Account::createWithAttributes(['name' => 'Luke']);
2Account::createWithAttributes(['name' => 'Leia']);
4$account = Account::where(['name' => 'Luke'])->first();
5$anotherAccount = Account::where(['name' => 'Leia'])->first();

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.

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.

Laravel News Partners