laravel orderby数组_Laravel 最佳实践

本文介绍了Laravel开发中遵循的最佳实践,包括单一职责原则、使用自定义Request类进行验证、业务代码放入服务层、避免重复代码、使用ORM而非SQL、避免在模板中查询等,旨在提高代码可读性和可维护性。
摘要由CSDN通过智能技术生成
ce82a5f9ae7c0e579fce23c2bcb04f1e.png

单一职责原则

一个类和一个方法应该只有一个责任。

例如:

public function getFullNameAttribute(){ if (auth()->user() && auth()->user()->hasRole('client') && auth()->user()->isVerified()) { return 'Mr. ' . $this->first_name . ' ' . $this->middle_name . ' ' . $this->last_name; } else { return $this->first_name[0] . '. ' . $this->last_name; }}

更优的写法:

public function getFullNameAttribute(){ return $this->isVerifiedClient() ? $this->getFullNameLong() : $this->getFullNameShort();}public function isVerifiedClient(){ return auth()->user() && auth()->user()->hasRole('client') && auth()->user()->isVerified();}public function getFullNameLong(){ return 'Mr. ' . $this->first_name . ' ' . $this->middle_name . ' ' . $this->last_name;}public function getFullNameShort(){ return $this->first_name[0] . '. ' . $this->last_name;}

保持控制器的简洁

如果您使用的是查询生成器或原始SQL查询,请将所有与数据库相关的逻辑放入Eloquent模型或Repository类中。

例如:

public function index(){ $clients = Client::verified() ->with(['orders' => function ($q) { $q->where('created_at', '>', Carbon::today()->subWeek()); }]) ->get(); return view('index', ['clients' => $clients]);}

更优的写法:

public function index(){ return view('index', ['clients' => $this->client->getWithNewOrders()]);}class Client extends Model{ public function getWithNewOrders() { return $this->verified() ->with(['orders' => function ($q) { $q->where('created_at', '>', Carbon::today()->subWeek()); }]) ->get(); }}

使用自定义Request类来进行验证

把验证规则放到 Request 类中.

例子:

public function store(Request $request){ $request->validate([ 'title' => 'required|unique:posts|max:255', 'body' => 'required', 'publish_at' => 'nullable|date', ]); ....}

更优的写法:

public function store(PostRequest $request){ 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值