We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
引用自laravel-best-practices
单一职责原则
保持控制器的简洁
使用自定义Request类来进行验证
业务代码要放到服务层中
DRY原则 不要重复自己
使用ORM而不是纯sql语句,使用集合而不是数组
集中处理数据
不要在模板中查询,尽量使用惰性加载
注释你的代码,但是更优雅的做法是使用描述性的语言来编写你的代码
不要把 JS 和 CSS 放到 Blade 模板中,也不要把任何 HTML 代码放到 PHP 代码里
在代码中使用配置、语言包和常量,而不是使用硬编码
使用社区认可的标准Laravel工具
遵循laravel命名约定
尽可能使用简短且可读性更好的语法
使用IOC容器来创建实例 而不是直接new一个实例
避免直接从 .env 文件里获取数据
.env
使用标准格式来存储日期,用访问器和修改器来修改日期格式
其他的好建议
一个类和一个方法应该只有一个责任。
例如:
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 类中.
例子:
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->articleService->handleUploadedImage($request->file('image')); .... } class ArticleService { 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('user', 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('user', function ($q) { $q->active(); })->get(); }
使用Eloquent可以帮您编写可读和可维护的代码。 此外Eloquent还有非常优雅的内置工具,如软删除,事件,范围等。
SELECT * FROM `articles` WHERE EXISTS (SELECT * FROM `users` WHERE `articles`.`user_id` = `users`.`id` AND EXISTS (SELECT * FROM `profiles` WHERE `profiles`.`user_id` = `users`.`id`) AND `users`.`deleted_at` IS NULL) AND `verified` = '1' AND `active` = '1' ORDER BY `created_at` DESC
Article::has('user.profile')->verified()->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 (User::all() as $user) {{ $user->profile->name }} @endforeach
更优的写法 (对于100个用户,使用以下写法只需执行2次DB查询):
$users = User::with('profile')->get(); ... @foreach ($users as $user) {{ $user->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->session()->get('cart'); $request->input('name');
session('cart'); $request->name;
更多示例:
Session::get('cart')
session('cart')
$request->session()->get('cart')
Session::put('cart', $data)
session(['cart' => $data])
$request->input('name'), Request::get('name')
$request->name, request('name')
return Redirect::back()
return back()
is_null($object->relation) ? null : $object->relation->id
optional($object->relation)->id
return 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()
->select('id', 'name')->get()
->get(['id', 'name'])
->first()->name
->value('name')
创建新的类会让类之间的更加耦合,使得测试越发复杂。请改用IoC容器或注入来实现。
$user = new User; $user->create($request->validated());
public function __construct(User $user) { $this->user = $user; } .... $this->user->create($request->validated());
将数据传递给配置文件,然后使用config()帮助函数来调用数据
config()
$apiKey = env('API_KEY');
// config/api.php 'key' => env('API_KEY'), // Use 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') }}
// Model protected $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 }}
The text was updated successfully, but these errors were encountered:
No branches or pull requests
引用自laravel-best-practices
内容
单一职责原则
保持控制器的简洁
使用自定义Request类来进行验证
业务代码要放到服务层中
DRY原则 不要重复自己
使用ORM而不是纯sql语句,使用集合而不是数组
集中处理数据
不要在模板中查询,尽量使用惰性加载
注释你的代码,但是更优雅的做法是使用描述性的语言来编写你的代码
不要把 JS 和 CSS 放到 Blade 模板中,也不要把任何 HTML 代码放到 PHP 代码里
在代码中使用配置、语言包和常量,而不是使用硬编码
使用社区认可的标准Laravel工具
遵循laravel命名约定
尽可能使用简短且可读性更好的语法
使用IOC容器来创建实例 而不是直接new一个实例
避免直接从
.env
文件里获取数据使用标准格式来存储日期,用访问器和修改器来修改日期格式
其他的好建议
单一职责原则
一个类和一个方法应该只有一个责任。
例如:
更优的写法:
🔝 返回目录
保持控制器的简洁
如果您使用的是查询生成器或原始SQL查询,请将所有与数据库相关的逻辑放入Eloquent模型或Repository类中。
例如:
更优的写法:
🔝 返回目录
使用自定义Request类来进行验证
把验证规则放到 Request 类中.
例子:
更优的写法:
🔝 返回目录
业务代码要放到服务层中
控制器必须遵循单一职责原则,因此最好将业务代码从控制器移动到服务层中。
例子:
更优的写法:
🔝 返回目录
DRY原则 不要重复自己
尽可能重用代码,SRP可以帮助您避免重复造轮子。 此外尽量重复使用Blade模板,使用Eloquent的 scopes 方法来实现代码。
例子:
更优的写法:
🔝 返回目录
使用ORM而不是纯sql语句,使用集合而不是数组
使用Eloquent可以帮您编写可读和可维护的代码。 此外Eloquent还有非常优雅的内置工具,如软删除,事件,范围等。
例子:
更优的写法:
🔝 返回目录
集中处理数据
例子:
更优的写法:
🔝 返回目录
不要在模板中查询,尽量使用惰性加载
例子 (对于100个用户,将执行101次DB查询):
更优的写法 (对于100个用户,使用以下写法只需执行2次DB查询):
🔝 返回目录
注释你的代码,但是更优雅的做法是使用描述性的语言来编写你的代码
例子:
加上注释:
更优的写法:
🔝 返回目录
不要把 JS 和 CSS 放到 Blade 模板中,也不要把任何 HTML 代码放到 PHP 代码里
例子:
更好的写法:
在Javascript文件中加上:
当然最好的办法还是使用专业的PHP的JS包传输数据。
🔝 返回目录
在代码中使用配置、语言包和常量,而不是使用硬编码
例子:
更优的写法:
🔝 返回目录
使用社区认可的标准Laravel工具
强力推荐使用内置的Laravel功能和扩展包,而不是使用第三方的扩展包和工具。
如果你的项目被其他开发人员接手了,他们将不得不重新学习这些第三方工具的使用教程。
此外,当您使用第三方扩展包或工具时,你很难从Laravel社区获得什么帮助。 不要让你的客户为额外的问题付钱。
🔝 返回目录
遵循laravel命名约定
来源 PSR standards.
另外,遵循Laravel社区认可的命名约定:
ArticlesControllerarticle/1users.show-active, show-active-usersUsersarticleComments, article_commentarticleComment, article_commentsarticle_comment, articleCommentsuser_article, articles_usersMetaTitle; article_meta_title$model->createdAtArticleId, id_article, articles_idcustom_id2017_01_01_000000_articlesget_allsaveArticletest_guest_cannot_see_article$articles_with_author$active, $data$users, $objArticlesEnabled; articles-enabledshowFiltered.blade.php, show_filtered.blade.phpgoogleCalendar.php, google-calendar.phpAuthenticatable, IAuthenticationNotificationTrait🔝 返回目录
尽可能使用简短且可读性更好的语法
例子:
更优的写法:
更多示例:
Session::get('cart')
session('cart')
$request->session()->get('cart')
session('cart')
Session::put('cart', $data)
session(['cart' => $data])
$request->input('name'), Request::get('name')
$request->name, request('name')
return Redirect::back()
return back()
is_null($object->relation) ? null : $object->relation->id
optional($object->relation)->id
return 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()
->select('id', 'name')->get()
->get(['id', 'name'])
->first()->name
->value('name')
🔝 返回目录
使用IOC容器来创建实例 而不是直接new一个实例
创建新的类会让类之间的更加耦合,使得测试越发复杂。请改用IoC容器或注入来实现。
例子:
更优的写法:
🔝 返回目录
避免直接从
.env
文件里获取数据将数据传递给配置文件,然后使用
config()
帮助函数来调用数据例子:
更优的写法:
🔝 返回目录
使用标准格式来存储日期,用访问器和修改器来修改日期格式
例子:
更优的写法:
The text was updated successfully, but these errors were encountered: