一个类和一个方法应该只有一个责任。
例如:
public function getfullnameattribute(){ if (auth()->ur() && auth()->ur()->hasrole('client') && auth()->ur()->isverified()) { return 'mr. ' . $this->first_name . ' ' . $this->middle_name . ' ' . $this->last_name; } el { return $this->first_name[0] . '. ' . $this->last_name; }}更优的写法:
public function getfullnameattribute(){ return $this->isverifiedclient() ? $this->getfullnamelong() : $this->getfullnameshort();}public function isverifiedclient(){ return auth()->ur() && auth()->ur()->hasrole('client') && auth()->ur()->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' => $client像的比喻句s]);}更优的写法:
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 类中.
例子:
public function store(request $request){ $request->validate([ 'title' => 'required|unique:posts|max:255', 'body' => 'required', 'publish_at' => 'nullable|date', ]); ....}更优的写法:
public function store(postrequest $request){ ....}class postrequest extends request{ public function rules() { return [ 'title' => 'required|unique:posts|max:255', 'body' => 'required', 'publish_at' => 'nullable|date', ]; }}控制器必须遵循单一职责原则,因此最好将业务代码从控制器移动到服务层中。
例子:
public function store(request $request){ if ($request->hasfile('image')) { $request->file('image')->move(public_path('images') . 'temp'); } ....}更优的写法:
public function store(request $request){ $this->articlervice->handleuploadedimage($request->file('image')); ....}class articlervice{ public function handleuploadedimage($image) { if (!is_null($image)) { $image->move(public_path('images') . 'temp'); } }}尽可能重用代码,srp可以帮助您避免重复造轮子。 此外尽量重复使用blade模板,使用eloquent的 scopes 方法来实现代码。
例子:
public function getactive(){ return $this->where('verified', 1)->wherenotnull('deleted_at')->get();}public function getarticles(){ return $this->wherehas('ur', function ($q) { $q->where('verified', 1)->wherenotnull('deleted_at'); })->get();}更优的写法:
public function scopeactive($q){ return $q->where('verified', 1)->wherenotnull('deleted_at');}public function getactive(){ return $this->active()->get();}public function getarticles(){ return $this->wherehas('ur', function ($q) { $q->active(); })->get();}使用eloquent可以帮您编写可读和可维护的代码。 此外eloquent还有非常优雅的内置工具,如软删除,事件,范围等。
例子:
lect *from `articles`where exists (lect * from `urs` where `articles`.`ur_id` = `urs`.`id` and exists (lect * from `profiles` where `profiles`.`ur_id` = `urs`.`id`) and `urs`.`deleted_at` is null)and `verified` = '1'and `active` = '1'order by `created_at` desc
更优的写法:
article::has('ur.profile')->verif自由交配ied()->latest()->get();例子:
$article = new article;$article->title = $request->title;$article->content = $request->content;$article->verified = $request->verified;// add category to article$article->category_id = $category->id;$article->save();
更优的写法:
$category->article()->create($request->validated());
例子 (对于100个用户,将执行101次db查询):
@foreach (ur::all() as $ur) {{ $ur->profile->name }}@endforeach更优的写法 (对于100个用户,使用以下写法只需执行2次db查询):
$urs = ur::with('profile')->get();...@foreach ($urs as $ur) {{ $ur->profile->name }}@endforeach例子:
if (count((array) $builder->getquery()->joins) > 0)
加上注释:
// 确定是否有任何连接if (count((array) $builder->getquery()->joins) > 0)
更优的写法:
if ($this->hasjoins())
例子:
let article = `{{ json_encode($article) }}`;更好的写法:
<input id="article" type="hidden" value="@json($article)">or<button class="js-fav-article" data-article="@json($article)">{{ $article->name }}<button>在javascript文件中加上:
let article = $('#article').val();当然最好的办法还是使用专业的php的js包传输数据。
例子:
public function isnormal(){ return $article->type === 'normal';}return back()->with('message', 'your article has been added!');更优的写法:
public function isnormal(){ return $article->type === article::type_normal;}return back()->with('message', __('app.article_added'));强力推荐使用内置的laravel功能和扩展包,而不是使用第三方的扩展包和工具。
如果你的项目被其他开发人员接手了,他们将不得不重新学习这些第三方工具的使用教程。
此外,当您使用第三方扩展包或工具时,你很难从laravel社区获得什么帮助。 不要让你的客户为额外的问题付钱。
来源 psr standards.
另外,遵循laravel社区认可的命名约定:
例子:
$request->ssion()->get('cart');$request->input('name');更优的写法:
ssion('cart');$request->name;更多示例:
ssion::get('cart')ssion('cart')$request->ssion()->get('cart')ssion('cart')ssion::put('cart', $data)ssion(['cart' => $data])$request->input('name'), request::get('name')$request->name, request('name')return redirect::back()return back()is_null($object->relation) ? null : $object->relation->idoptional($object->relation)->idreturn view('index')->with('title', $title)->with('client', $client)return view('index', compact('title', 'client'))$request->has('value') ? $request->value : 'default';$request->get('value', 'default')carbon::now(), carbon::today()now(), today()app::make('class')app('class')->where('column', '=', 1)->where('column', 1)->orderby('created_at', 'desc')->latest()->orderby('age', 'desc')->latest('age')->orderby('created_at', 'asc')->oldest()->lect('id', 'name')->get()->get(['id', 'name'])->first()->name->value('name')创建新的类会让类之间的更加耦合,使得测试越发复杂。请改用ioc容器或注入来实现。
例子:
$ur = new ur;$ur->create($request->validated());
更优的写法:
public function __construct(ur $ur){ $this->ur = $ur;}....$this->ur->create($request->validated());.env 文件里获取数据将数据传递给配置文件,然后使用config()帮助函数来调用数据
例子:
$apikey = env('api_key');更优的写法:
// config/api.php'key' => env('api_key'),// u the data$apikey = config('api.key');例子:
{{ carbon::createfromformat('y-d-m h-i', $object->ordered_at)->todatestring() }}{{ carbon::createfromformat('y-d-m h-i', $object->ordered_at)->format('m-d') }}更优的写法:
// modelprotected $dates = ['ordered_at', 'created_at', 'updated_at'];public function getsomedateattribute($date){ return $date->format('m-d');}// view{{ $object->ordered_at->todatestring() }}{{ $object->ordered_at->some_date }}永远不要在路由文件中放任何的逻辑代码。
尽量不要在blade模板中写原始 php 代码。
原文作者:
原文链接:https://github.com/alexeymezenin/laravel-best-practices/
本文发布于:2023-04-07 13:08:26,感谢您对本站的认可!
本文链接:https://www.wtabcd.cn/fanwen/zuowen/066df4d4ef6f1ff1c15de08d65655841.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文word下载地址:Laravel 最佳实践.doc
本文 PDF 下载地址:Laravel 最佳实践.pdf
| 留言与评论(共有 0 条评论) |