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.
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
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 directory 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 acts the
MoneySubtracted 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