Implementing Event Sourcing PHP Application in 15 minutes

Implementing Event Sourcing PHP Application in 15 minutes

In this post we will jump straight to the code and we will implement Event Sourcing Application in 15 minutes.
The only thing worth to read before starting is general idea of Event Sourcing from previous post.
There is no time to be wasted, so let's start.

1st minute - Setting up project

  1. Create empty catalog "App" and run "composer init" inside. Name the application "ecotone/app" and make use of defaults.
    After processing we should have composer.json:
    "name": "ecotone/app",
    "autoload": {
        "psr-4": {
            "Ecotone\\App\\": "src/"
    "require": {}

2. Now let's require Ecotone Lite package for Event Sourcing

composer require ecotone/lite-event-sourcing-starter

3rd minute - Implementation

We will create electronic Wallet, that will keep log of all transactions.
We will do In Memory implementation to not waste any time on database configuration.

Ecotone is powered up by well tested and solid Prooph Event Store for storing Events.  
Besides In Memory implementation, we can switch to PostgreSQL/MySQL/MariaDB.

We will have three possible actions on Wallet:

  1. Registering new Wallet
  2. Adding money to Wallet
  3. Subtracting money from Wallet
Remember that we are in Event Sourcing world, so after performing action, we return Events.
If we want to rebuild the state from previous events in order to validate if given action can be performed, we can implement method like onWalletWasRegistered.

Let's see how our events looks like:

9th minute - Building Projection

So now we want to be able to answer question, what is the current amount of money on given wallet. To do it we will make use of projection, which subscribe to events and do the calculations.

Our projection recalculate the current wallet balance, whenever event happens.
It also expose possibility to query it by "getWalletBalance".

13th minute - Running the example

We will now register the Wallet and then add 100 and subtract 40.
Our Projection should tell us after those events will happen, that the current amount is 60.

Create in the root of the project file called "run_example.php"

Now, when we run it, the result will be 60.

15th minute - Summary

We have built Event Sourced Wallet.
Ecotone aims for straight forward configuration. We have only defined the classes that are needed for this functionality, the amount of configuration is minimal.
Thanks to that we can quickly implement new functionalities and keep our code clean.

If you want to follow on Ecotone Framework go here.
If you want to see above implementation go to this repository.

> >