![ce82a5f9ae7c0e579fce23c2bcb04f1e.png](https://i-blog.csdnimg.cn/blog_migrate/c3584328a6e9a5676052804361c1acfd.jpeg)
单一职责原则
一个类和一个方法应该只有一个责任。
例如:
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){