Where to put common business logic in DDD with MVC
https://softwareengineering.stackexchange.com/questions/301615
-
21-10-2020 - |
Question
Providing I have the following scenario: I have a Web application where users can deposit money to their accounts (wire transfer). When a user deposits money to their account, they should click the "Refresh my balance" button to refresh their balance.
The business logic behind the "Refresh my balance" is the following:
- Refresh balance, for example by calling a bank's webservice.
- If there is new money, subtract a % from it as a fee.
The thing is that I would not like to allow refreshing balance without proceeding new deposit fees.
I have two services:
class AccountService
{
//The following calls the bank webservice to get the new balance and updates the account entity
public function refreshBalance(Account account);
}
class FeeService
{
//The following checks if there are deposits, and if there are it subtract a fee
public function proceedNewFees(Account account);
}
My MVC controller action is the following right now:
public function refreshBalanceAction()
{
$account = $this->accountService->getAuthenticatedAccount();
$this->accountService->refreshBalance($account);
$this->accountService->proceedNewFees($account);
}
As you can see, in the controller I have some business logic. I would like to move it to the Domain layer. Where is the best place to put this business logic from the controller? Create a new CommonLogicService? Implement it in the AccountModel (and if so, how to refer to the AccountService instance being in the AccountModel? DI?)?
Solution
The way you describe it, I would put the code to update the balance in a separate UpdateBalanceService-class. Then create a new class 'RefreshBalanceService' that contains both the UpdateBalanceService and a ProcessNewFeesService. The UpdateBalanceService-class would then call both services and perform the necessary actions. It is then a matter of implementing your refresh-code so that it uses the UpdateBalanceService class to do its work, which will in turn delegate to the subservices to perform its tasks.