F
F
fjq2022-01-14 07:02:17
PHP
fjq, 2022-01-14 07:02:17

DDD Transactions in Application Service?

Good afternoon, I'm not an expert in DDD and I don't understand all the subtleties, please tell me how the launch of transactions is implemented in the Application Service?
There is a structure:

src-
    - Module1
          - Application
               - BooService
               - FooService
          - Domain
             - Repository
                   - MyModelRepositoryInterface
          - Infrastructure
               - ExampleCommand
               - Repository
                   - MyModelRepository
    - Module2
          - Application
          - Domain
          - Infrastructure


The \App\Module1\Infrastructure\ExampleCommand command is launched
, which in turn starts the \App\Module1\Application\BooService service
, it accesses the MyModelRepository repository and receives some abstract data from the FooService service and then an object is created and saved.

How is a transaction implemented in this service? and in general is it possible here or is it necessary to build the architecture in some other way?
Either some kind of TransactionService service at the Infrastructure level with an interface in Domain or work through Events comes to mind.
class BooService 
{
    public function execute()
    {

        //Transaction start
        
        $result = $this->fooService->execute();
        $this->myModelRepository->add(new MyModel($result->foo, $result->boo));

        //Transaction finish
        
        return true;
    }

}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
ivan_k11, 2022-01-14
@ivan_k11

Transactions are the level of infrastructure
"with an interface in the Domain", the domain should not know anything about transactions.
It is possible to propose such a solution
Application

$repository->transactional(
            static function () use (
                $repository
            ) {
                $repository->save($entity);
                //и прочее сохранение данных
            }
        );

And in the infrastructure, implement the method
public function transactional(\closure $func)
    {
        $db_connection = getDbConnection();
        $db_connection->startTransaction();
        $func();
        $db_connection->commitTransaction();
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question