I have an entity that has a dollar
balance property. Whenever an event occurs that causes the balance to change, such as a debit, within the same transaction the
balance should be decremented by the amount of the debit (as a sort of "summary" value, so that a DB query won't need to be performed to retrieve the balance every time.)
There are two ways to do this:
- I can use
lock for updatefunctionality in the DB to prevent any reads from the
balancevalue until it finishes processed. That way, I can change the balance in my entity, such as
$user->lowerBalance(1000), and then commit the value in a repository. The downside is this can be a high-load application, and I don't want to stop anyone from reading the value.
- The other option is to use the database's decrement feature:
update users set balance = balance - 1000. This will ensure that even if two updates are made at nearly the same time, the value will always be correct. The actual value will not be set or known in the domain layer until it queried.
I want to use option 2, but how do I model this? One way is to call the repository's method from within the
lowerBalance() method in the Entity's class, but then I've coupled the domain entity to the infrastructure layer. Plus, if I want the latest value, I'd need to ensure the repository re-fetches the entity. Maybe it's ok in this case, as the blue book says that layers can depend on the layers below them.
Any suggestions on how this can be structured?