提升 Laravel 代码质量的 6 个实用技巧
在使用任何编程语言或框架时,您都可以运用一些技巧来提升编码水平,使应用程序性能更佳,代码更优雅。您越是遵循某些设计原则和最佳实践,您的开发能力就会提升得越快。作为一名专业的 Laravel/Vue 开发者,我创建了一个名为 laravelbit 的免费资源,每周都会发布 Laravel 使用技巧。在本文中,我将向您展示其中的一些技巧,希望它们能帮助您大幅提升 Laravel 应用程序的性能。让我们开始吧!
1. 使用 Eloquent 查询作用域,让你的代码更优雅
在 Laravel 应用中使用 Eloquent ORM 时,我们经常需要在处理数据时满足某些条件。例如,考虑以下查询:
$active_administrators = User::where('active', '=', 1)->where('is_admin', '=', 1)->get();
我们可以在应用程序的许多地方轻松使用这些条件。为了使代码更易读且避免重复,我们可以使用 查询作用域。例如,我们可以在 User 模型中创建以下函数:
public function scopeActive($query)
{
return $query->where('active', '=', 1);
}
public function scopeAdmin($query)
{
return $query->where('is_admin', '=', 1);
}
现在,我们最初的查询语句如下所示:
$active_administrators = User::active()->admin()->get();
2. 在创建模型时自动设置列值
有些情况下,您可能希望在创建新记录时自动设置某个列的值。为了实现这一点,您可以 在模型的boot方法中使用模型的creating 事件 。在本例中,我们将 Invoice 模型中每个新创建记录的 paid 列的值设置为 0(false):
class Invoice extends Model {
protected static function boot()
{
parent::boot();
Invoice::creating(function($model) {
$model->paid = 0;
});
}
}
3. 使用可选的辅助函数来避免错误
访问对象值时,如果该对象为空,则代码会引发错误。例如:
return $invoice->total;
如果发票对象为空,则会引发错误。避免错误的一个简单方法是使用 Laravel 的可选 辅助函数:
return optional($invoice)->total;
现在,如果 `$invoice` 对象为空,你的代码将返回 `null` 而不是抛出错误。你还可以使用带有可选辅助函数的闭包。该辅助函数接收闭包本身作为第二个参数,如果第一个参数不为空,则会调用该闭包。
return optional(Invoice::find($id), function ($invoice) {
return $invoice->total;
});
4. 自动删除相关记录
在设计应用程序数据库时,创建关联表是很常见的做法。删除父记录时,同时删除关联的子记录也是标准做法,也是良好的数据库设计原则。在 Laravel 中,我们可以 在模型的 ` boot`方法中使用模型的 ` deleting` 事件 来实现这一点 。例如,要删除发票中的所有项目:
class Invoice extends Model
{
public function items()
{
return $this->hasMany('\App\Models\Item');
}
public static function boot() {
parent::boot();
static::deleting(function($invoice) {
foreach ($invoice->items as $item) {
$item->delete();
}
});
}
}
5. 更新或创建
在使用数据库时,经常需要检查某个记录是否存在,并根据情况更新它,否则创建新记录。例如:
$invoice = Invoice::where('active', 1)
->where('client', 'My client')
->where('price', 49)
->first();
if ($invoice) {
$invoice->update(['price' => 29]);
}
您可以使用 Eloquent 的updateOrCreate方法代替:
$invoice = Invoice::updateOrCreate(
['active' => '1', 'client' => 'My client'],
['price' => 29]
);
6. 使用 Laravel 集合方法
集合(Collections)是 Laravel 提供的一项强大功能,它允许我们轻松操作数组数据类型。这可以节省大量时间,并且语法简洁直观。尤其是在与 Eloquent 结合使用时,它非常有用。例如,如果您有一个如下的 Eloquent 查询:
$invoices = Invoice::where('active', 1)
->orderBy('total')
->take(10)
->get()
或许我们希望从数据库筛选列表中移除所有已付款的发票;本质上,就是筛选出未付款的发票。我们可以使用 Collection 的 reject 方法:
$activeInvoices = $invoices->reject(function ($invoice) {
return $invoice->paid;
});
我们也可以使用 filter 方法来完成同样的任务:
$activeInvoices = $invoices->filter(function ($invoice) {
return $invoice->paid;
});
再举一个例子,让我们从集合中获取符合某个条件的第一个元素:
$activeInvoices = $invoices->first(function ($invoice) {
return $invoice->paid;
});
在开发应用程序时运用这类技巧非常重要,因为它可以提高代码效率和可读性。如果您想定期获取新的 Laravel 技巧,请访问laravelbit。
文章来源:https://dev.to/lukapg/6-useful-tips-to-boost-your-laravel-code-nbp