如何在Laravel的一个控制器中应用交易两个服务
我有两个模型X和Y。对于这些模型,我也有一个服务和存储库。
结构是:
| App
|| Http
||| Controller
|||| XController
|||| YController.php
| Service
|| XService.php
|| YService.php
| Repository
|| XRepository.php
|| YRepository.php
还可以。现在,我有第三个控制器z(与模型断开)。
| App
|| Http
||| Controller
|||| XController
|||| YController.php
|||| ZController.php <!--- THIS
| Service
|| XService.php
|| YService.php
| Repository
|| XRepository.php
|| YRepository.php
在ZController中,我必须通过两个服务(Xservice和Yservice)来回忆起创建方法。
class ZController extends Controller
{
protected XService $XService;
protected YService $YService;
public function __construct(XService $XService, YService $YService)
{
$this->XService = $XService;
$this->YService = $YService;
}
public function store(Request $request): JsonResponse
{
$x = $this->XService->create();
$y = $this->YService->create();
}
}
我的问题是:如果$ y的服务失败(例外),我还必须删除$ x的插入。如果我输入DB ::交易将在交易嫁接给他人时会产生错误。我可以应用什么解决方案?
而且,我可以在存储库或服务中应用试验吗?还是在特定情况下?
I have a two model X and Y. For the models I also have a Service and Repository.
The structure is:
| App
|| Http
||| Controller
|||| XController
|||| YController.php
| Service
|| XService.php
|| YService.php
| Repository
|| XRepository.php
|| YRepository.php
Ok. Now I have a third controller Z (disconnected from the model).
| App
|| Http
||| Controller
|||| XController
|||| YController.php
|||| ZController.php <!--- THIS
| Service
|| XService.php
|| YService.php
| Repository
|| XRepository.php
|| YRepository.php
In the ZController I must recall the create method by two services (XService and YService).
class ZController extends Controller
{
protected XService $XService;
protected YService $YService;
public function __construct(XService $XService, YService $YService)
{
$this->XService = $XService;
$this->YService = $YService;
}
public function store(Request $request): JsonResponse
{
$x = $this->XService->create();
$y = $this->YService->create();
}
}
The problem I have is that: if the service of $y fails (Exception), I must also delete the insertion of $x. If I enter the DB::transaction generates an error when it is a transaction grafted to others. What solution can I apply?
And, the try catch can i apply inside the repository or service? Or in both for particular situation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
PHP不支持多个继承,但是通过在PHP中使用接口或使用PHP中的特征而不是类中的特征,Laravel也是如此,如果您不想浏览存储库,则可以使用简单的特征来完成任务。
PHP doesn’t support multiple inheritance but by using Interfaces in PHP or using Traits in PHP instead of classes ,same Goes with Laravel ,If you Don't want to go through making repository ,then you can use simple traits for the task .