Home > Article > PHP Framework > Let's talk about how to use database transactions correctly in Laravel code
In web development, data integrity and accuracy are very important. Therefore, we must ensure that the code we write can store, update, and delete data in the database in a safe manner.
In this article, we will look at what database transactions are, why they are important, and how to start using them in Laravel. We'll also look at a common "problem" involving queues and database transactions.
Before we start looking into Laravel’s database transactions, let’s first look at what they are and how they work Useful.
There are many complex-sounding technical explanations of what a database transaction is. However, for most web developers, all we need to know is that transactions are how an entire unit of work in a database is completed.
To understand what this actually means, let's look at a basic example that will give a little context.
Suppose we have an application that allows users to register. Whenever a user signs up, we want to create a new account for them and then assign them a default role of "general".
Our code might look like this:
$user = User::create([ 'email' => $request->email, ]); $user->roles()->attach(Role::where('name', 'general')->first());
At first glance, this code seems completely fine. However, when we look closer, we can see that there are actually a few things that can go wrong. We can create users, but we cannot assign roles to them. This could be caused by many different reasons, such as a bug in the code that assigns the role, or even a hardware issue that prevents us from reaching the database.
As this happens, it will mean that there will be a user without a role in the system. As you can imagine, this can cause exceptions and bugs elsewhere in your application, since you always assume the user has a role (which is correct).
So, in order to solve this problem, we can use database transactions. By using transactions, it ensures that if any error occurs while executing the code, any changes to the database inside the transaction will be rolled back. For example, if a user is inserted into the database, but the query to assign the role fails for any reason, then the transaction will be rolled back and the user's row will be deleted. By doing this, it means that we cannot create users without assigned roles.
In other words, it’s “all or nothing.”
Now that we have a simple idea of what transactions are and what they implement, let’s Let's see how to use them in Laravel.
In Laravel, it is actually very easy to start using transactions since we have access to the transaction()
method on the DB
facade. Continuing with the previous example code, let's see how transactions are used when creating users and assigning roles to them.
use Illuminate\Support\Facades\DB; DB::transaction(function () use ($user, $request): void { $user = User::create([ 'email' => $request->email, ]); $user->roles()->attach(Role::where('name', 'general')->first()); });
Now our code is wrapped in a database transaction, and if an exception is thrown at any point in it, any changes to the database will be returned to the state before the transaction started.
Sometimes, you may want to have more granular control over transactions. For example, let's say you're integrating with a third-party service like Mailchinp or Xero. We would say that whenever you create a new user, you also need to make an HTTP request to their API to create them as a user in that system as well.
We may want to update our code so that if we are unable to create a user in our own system ** and ** in a third party system, neither system creates the user. If you're interacting with a third-party system, you probably have a class that you can use to make requests. Alternatively, there may be a package you can use. Sometimes, when some requests cannot be completed, the requesting class may throw an exception. However, some of these classes may eliminate the error and simply return false
from the method you call, placing the error in a field of the class.
So let's assume we have the following basic example class that calls the API:
class ThirdPartyService { private $errors; public function createUser($userData) { $request = $this->makeRequest($userData); if ($request->successful()) { return $request->body(); } $errors = $request->errors(); return false; } public function getErrors() { return $this->errors; } }
Of course, the above request class code is incomplete, and my code example below is not very clear, but It should give you a rough idea of the point I'm trying to make. So let's use this request class and add it to our previous code example:
use Illuminate\Support\Facades\DB; use App\Services\ThirdPartyService; DB::beginTransaction(); $thirdPartyService = new ThirdPartyService(); $userData = [ 'email' => $request->email, ]; $user = User::create($userData); $user->roles()->attach(Role::where('name', 'general')->first()); if ($thirdPartyService->createUser($userData)) { DB::commit(); return; } DB::rollBack(); report($thirdPartyService->getErrors());
Looking at the code above, we can see that we started a transaction, created the user and assigned them a role, and then we called the third-party service. If the user is successfully created in the external service, we can safely commit the database changes knowing that everything has been created correctly. However, if the user is not created in the external service, the changes in the database are rolled back (the user and his role assignments are deleted), and then an error is reported.
作为一个额外的技巧,我通常建议将任何影响第三方系统、文件存储或缓存的代码放在数据库调用之后。
为了更深入地理解这一点,让我们以上面的代码示例为例。请注意,在向第三方服务发出请求之前,我们是如何首先对数据库进行所有更改的。这意味着,如果从第三方请求返回任何错误,将回滚我们自己数据库中的用户和角色分配。
然而, 如果我们反过来做,我们在修改数据库之前发出请求,那就不是这种情况了。出于任何原因,如果我们在数据库中创建用户时发生任何错误,我们会在第三方系统中创建一个新用户,但是在我们系统中却没有创建。如你所想, 这可能会导致更多问题。通过编写一个清理方法将用户从第三方系统中删除,可以降低这个问题的严重性。 但是,正如您可以想象的那样, 这可能会导致更多的问题,并导致编写、维护和测试更多的代码。
所以,我总是建议把数据库调用放在API调用之前。但并不总是这样,有时可能需要将第三方请求返回的值保存到数据库中。如果是这种情况,就需要API调用放到数据库调用之前了,只要您确保有一些代码可以处理任何失败,这是完全可以的。
同样值得注意的是,因为我们最初的示例使用DB:transaction()
方法,在抛出异常时回滚事务,所以我们也可以使用这种方法向我们的第三方服务发出请求。相反,我们可以这样更新类:
use Illuminate\Support\Facades\DB; use App\Services\ThirdPartyService; DB::transaction(function () use ($user, $request): void { $user = User::create([ 'email' => $request->email, ]); $user->roles()->attach(Role::where('name', 'general')->first()); if (! $thirdPartyService->createUser($userData)) { throw new \Exception('User could not be created'); } });
这绝对是一个可行的解决方案,并将按照预期成功回滚事务。事实上,就我个人的偏好而言,我实际上更喜欢这种方式,而不是手动使用事务。我认为它看起来更容易阅读和理解。
然而,与手动提交或回滚事务时使用 ‘if’ 语句相比,异常处理在时间和性能方面可能会比较昂贵。
因此,举个例子,如果这段代码用于导入包含10,000个用户数据的 CSV 文件,您可能会发现抛出异常会大大减慢导入速度。
但是,如果它只是在一个用户可以注册的简单web请求中使用,那么抛出异常可能没有问题。当然,这取决于应用程序的大小,性能是关键因素;所以你需要根据具体情况来决定。
每当您在事务中处理队列时,您都需要注意一个“陷阱”。
为了提供一些上下文,让我们继续使用之前的代码示例。我们可以想象,在我们创建了我们的用户之后,我们想要运行一个任务来提醒管理员通知他们新注册并向新用户发送欢迎电子邮件。我们将通过分派一个名为 AlertNewUser
的队列任务来做到这一点,如下所示:
use Illuminate\Support\Facades\DB; use App\Jobs\AlertNewUser; use App\Services\ThirdPartyService; DB::transaction(function () use ($user, $request): void { $user = User::create([ 'email' => $request->email, ]); $user->roles()->attach(Role::where('name', 'general')->first()); AlertNewUser::dispatch($user); });
当您开始一个事务并对其中的任何数据进行更改时,这些更改仅对正在运行事务的请求/进程可用。对于任何其他访问您更改的数据的请求或进程,必须先提交事务。因此,这意味着如果我们从事务内部分派任何排队的队列、事件监听器、邮件,通知或广播事件。由于竞争条件,我们的数据更改可能在事务内部不可用。
如果队列在事务提交之前开始处理排队的代码,就会发生这种情况。因此,这可能导致您的排队代码可能试图访问不存在的数据,并可能导致错误。在我们的例子中,如果在事务提交之前运行队列AlertNewUser
作业,那么我们的作业将尝试访问一个尚未实际存储在数据库中的用户。如您所料,这将导致作业失败。
为了防止这种竞争条件的发生,我们可以对我们的代码和/或我们的配置进行一些更改,以确保仅在事务成功提交后才调度队列。
我们可以更新 config/queue.php
并添加 after commit
字段。让我们想象一下,我们正在使用 redis
队列驱动程序,所以我们可以这样更新配置:
<?php return [ // ... 'connections' => [ // ... 'redis' => [ 'driver' => 'redis', // ... 'after_commit' => true, ], // ... ], // ... ];
通过进行此更改,如果我们尝试在事务内调度队列,则队列将在实际调度队列之前等待事务提交。 方便的是,如果事务回滚,它也会阻止队列被调度。
然而,可能有一个原因,您不希望在配置中全局设置此选项。 如果是这种情况,Laravel 仍然提供了一些很好的助手方法,我们可以根据具体情况使用它们。
如果我们想更新事务中的代码,只在任务提交后才分派任务,可以使用afterCommit()
方法,如下所示:
use Illuminate\Support\Facades\DB; use App\Jobs\AlertNewUser; use App\Services\ThirdPartyService; DB::transaction(function () use ($user, $request): void { $user = User::create([ 'email' => $request->email, ]); $user->roles()->attach(Role::where('name', 'general')->first()); AlertNewUser::dispatch($user)->afterCommit(); });
Laravel 还提供了另一个我们可以使用的方便的beforeCommit()
方法。 如果我们在队列配置中设置了全局after_commit => true
,但不关心等待事务被提交,就可以使用这个。 要做到这一点,我们可以简单地像这样更新我们的代码:
use Illuminate\Support\Facades\DB; use App\Jobs\AlertNewUser; use App\Services\ThirdPartyService; DB::transaction(function () use ($user, $request): void { $user = User::create([ 'email' => $request->email, ]); $user->roles()->attach(Role::where('name', 'general')->first()); AlertNewUser::dispatch($user)->beforeCommit(); });
希望本文能让您大致了解什么是数据库事务以及如何在 Laravel 中使用它们。 它还向您展示了如何在从内部事务调度队列时避免“陷阱”。
原文地址:https://dev.to/ashallendesign/using-database-transactions-to-write-safer-laravel-code-13ek
译文地址:https://learnku.com/laravel/t/61575
【相关推荐:laravel视频教程】
The above is the detailed content of Let's talk about how to use database transactions correctly in Laravel code. For more information, please follow other related articles on the PHP Chinese website!