Multiple Service Layers and Database Transactions(多个服务层和数据库事务)
问题描述
我只是想知道如何最好地处理跨多个服务层的事务.服务层使用 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.
这篇关于多个服务层和数据库事务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:多个服务层和数据库事务
基础教程推荐
- 超薄框架REST服务两次获得输出 2022-01-01
- Libpuzzle 索引数百万张图片? 2022-01-01
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01
- 在多维数组中查找最大值 2021-01-01
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01
- XAMPP 服务器不加载 CSS 文件 2022-01-01
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01