1
I’m doing a small project for learning purposes using Laravel, this system revolves around two "models", Conta
and Transacao
.
one Conta
has name and balance, a Transacao
has count_source, count_destination, value and details.
I created repositories and services for the two "Models" to encapsulate communication with Eloquent and Controller.
Sample structure of Transacao
class TransactionController extends Controller
{
public function transfer(Request $request, TransactionService $transactionService)
{
try {
$transactionService->transfer(
$request->from, $request->to, $request->amount, $request->details
);
return response()->json(['success' => 'true']);
} catch (\Throwable $error) {
return response()->json([
'success' => 'false',
'errors' => $error
], Response::BAD_REQUEST);
}
}
}
class TransactionService
{
public function findById(int $id, TransactionRepositoryContract $TransactionRepository)
{
return $TransactionRepository->findById($id);
}
public function transfer($from, $to, $amount, $details)
{
$TransactionEloquentRepository = new TransactionEloquentRepository;
$AccountEloquentRepository = new AccountEloquentRepository;
$fromAccount = $AccountEloquentRepository->findById($to);
if($fromAccount->getAmount() < $amount) {
throw new Exception('source account does not have enough balance');
}
//db transaction
$TransactionEloquentRepository->create([
'from' => $from
'to' => $to,
'amount' => $amount,
'details' => $details
]);
$AccountEloquentRepository->update($from, [
'balance' => $fromAccount->balance - $amount
]);
//db end transaction
}
}
The $TransactionEloquentRepository
basically just encapsulates a few calls to Eloquent.
The doubts are as follows:
1 - Is this implementation correct? the service that should handle these validations (check if an account is valid, if it has sufficient balance, create balance, decrease balance etc) and can communicate with external repositories?
1.1 - The Laravel has the validation with Formrequest, but this validation must also be in the service?
2 - In case of failure at any stage of this process, who should launch exceptions and treat exceptions? only the controller should handle?
3 - Is it wrong to use Eloquent transactions in Repositories? since considering abstraction, not all banks have the concept of transactions
Thank you very much for the answer, a question, in the case of transfer, would I inject the two repository interfaces into the Construct? because not all methods will use the Accountrepository. Or should I create a specific Service pro Transfer, and inject the two repository interfaces into it? Being: Transactioncontroller.transfer -> Transferservice -> Transaction and Account Repository in __Construct, and within Transferservice, another method, makeTransfer, which would handle these rules and release exceptions, good approach?
– Thiago