多个服务层和数据库事务
我只是想知道如何最好地处理跨多个服务层的事务.服务层使用 ORM 来存储和检索数据库.是否应该在各个服务层中了解和处理事务?还是应该由另一层处理?
I'm just wondering how to best handle transactions across multiple service layers. The service layers use an ORM to store and retrieve from the database. Should the transactions be known and handled within the individual service layers? Or should they be handled by another layer?
例如:我为用户和客户提供两个服务层.我想:
For example: I have two service layers for users and clients. I would like to:
1) 创建并保存一个新客户端
2) 创建并保存一个新用户
3) 将该用户分配给客户端
1) Create and save a new client
2) Create and save a new user
3) Assign that user to the client
所有在一个事务中.
一个简单的例子可能如下所示:
A simple example might look like this:
$userManagementService = new UserManagementService;
$newUserData = array(...);
$newUser = $userManagementService->create($newUserData);
$clientManagementService = new ClientManagementService;
$newClientData = array(...);
$newClient = $clientManagementService->create($newClientData);
$userManagementService->assignUserToClient($newUser, $newClient);
事务逻辑应该去哪里?
推荐答案
不要尝试在服务层或 ORM 内进行嵌套事务.
Do not try to do nested transactions within service layers or within the ORM.
事务对于数据库连接是全局的.除非您的 RDBMS 本身支持嵌套事务并且您的 DB API 公开嵌套事务,否则您可能会遇到异常情况.
Transactions are global to the DB connection. Unless your RDBMS supports nested transactions natively and your DB API exposes nested transactions, you can run into anomalies.
详情见我对的回答如何检测该事务已经开始?
由于您使用的是 PHP,因此您的事务范围至多是单个请求.所以你应该只使用容器管理的事务,而不是服务层事务.也就是说,在处理请求开始时启动事务,并在处理完请求时提交(或回滚).
Since you're using PHP, the scope of your transactions is at most a single request. So you should just use container-managed transactions, not service-layer transa. That is, start the transaction at the start of handling the request, and commit (or rollback) as you finish handling the request.
如果在嵌套的 ORM 操作中发生需要回滚的异常,则使用异常将其冒泡,并让容器(即您的 PHP 操作控制器)处理它.
If an exception requiring a rollback occurs deep within nested ORM actions, then bubble that up by using an Exception, and let the container (i.e. your PHP action controller) take care of it.
相关文章