Using projectors to transform events

Let’s build a bit further on the Larabank example mentioned in the previous section. The main drawback highlighted that example is the fact that when updating a value, we lose the old value. Let’s solve that problem.

Instead of directly updating the value in the database, we could write every change we want to make as an event in our database.

Here we write our first event in the database
When new events come in, we'll write them to the events table as well

All events get passed to a class we call a projector. The projector transforms the events to a format that is handy to use in our app. In our Larabank example, the events table hold the info of the individual transactions like MoneyAdded and MoneySubtracted. A projector could build an Accounts table based on those transactions.

Imagine that you’ve already stored some events, and your first projector is doing its job creating that Accounts table. The bank director now wants to know on which accounts the most transactions were performed. No problem, we could create another projector that reads all previous events and adds the MoneyAdded and MoneySubtracted events to make projections.

This package can help you store native Laravel events in a stored_events table and create projectors that transform those events.

Here’s our example app Larabank rebuild with projectors. In the AccountsController we’re not going to directly modify the database anymore. Instead, the controller will call methods which will in their turn fire off events. Our package will listen for those events (which implement the empty ShouldBeStored interface) and store them in the stored_events table. Those events will also get passed to all registered projectors. The AccountsProjector will build the Accounts table using a couple of events it listens for.

If you want to know more about projectors and how to use them, head over to the using-projectors section.