本文规范皆来自于Laravel官方项目Laravel.io,请酌情阅读
控制器
文件夹按照现实逻辑划分,以免过多复杂
控制内中间件
public function __construct()
{
$this->middleware([Authenticate::class, EnsureEmailIsVerified::class], ['except' => ['index', 'show']]);
}
将具体业务通过队列分发出去
public function delete(Article $article)
{
$this->authorize(ArticlePolicy::DELETE, $article);
$this->dispatchNow(new DeleteArticle($article));
$this->success('articles.deleted');
return redirect()->route('articles');
}
模型
字段判断
public function isPinned(): bool
{
return (bool) $this->is_pinned;
}
作用域查询
public function scopeSubmitted(Builder $query): Builder
{
return $query->whereNotNull('submitted_at');
}
字段转化为强类型
public function id(): int
{
return $this->id;
}
直接查询
public function latestArticles(int $amount = 10)
{
return $this->articles()->latest()->limit($amount)->get();
}
具体数据操作
public function deleteReplies()
{
foreach ($this->replyAble()->get() as $reply) {
$reply->delete();
}
}
常量定义
const DEFAULT = 1;
const MODERATOR = 2;
const ADMIN = 3;
在helper中建立trait,提高复用性
use App\Helpers\HasAuthor;
use App\Helpers\HasLikes;
use App\Helpers\HasSlug;
use App\Helpers\HasTags;
use App\Helpers\HasTimestamps;
任务队列
实现任何具体的相关与数据库交互的操作
实现过程
//定义
private $title;
//初始化
public function __construct(string $title, string $body, User $author, bool $shouldBeSubmitted, array $options = [])
{
$this->title = $title;
$this->body = $body;
}
//注入
public static function fromRequest(ArticleRequest $request): self
{
return new static(
$request->title(),
);
}
//具体操作
public function handle(): Article
{
//进行某些验证
$this->isOK();
$article = new Article([
'title' => $this->title,
]);
//直接调用模型具体操作
$article->updateSeries(Series::find($this->series));
$article->save();
return $article;
}
//验证
private function isOK()
{
try {
User::find(1);
} catch (ModelNotFoundException $exception) {
return true;
}
throw CannotCreateUser::isOK();
}
直接调用模型,这点很重要是在模型写那么函数的原因
$article->updateSeries(Series::find($this->series));
在进行具体操作前进行验证,直接调用exceptions中的类将错误抛出
<?php
namespace App\Exceptions;
use Exception;
final class CannotCreateUser extends Exception
{
public static function isOK(): self
{
return new static("The NO OK.");
}
}
-----------------------------------
//可能你不想要laravel自带的的报错返回,你可以自己重新构建
<?php
namespace App\Exceptions;
use Exception;
use Illuminate\Http\Request;
class ApiRequestExcept extends Exception
{
/**
* @var int http status code
*/
protected $statusCode;
public function __construct($message = "", $code = 0, $statusCode = 200)
{
$this->statusCode = $statusCode;
parent::__construct($message, $code);
}
public function render(Request $request)
{
return response([
'code' => $this->code,
'msg' => $this->message
])->setStatusCode($this->statusCode);
}
}
//在具体运用时进行调用
public static function beVoteUserNonexistence()
{
return new LkApiRequestExcept('该用户不存在');
}
查询语句
复杂的查询语句直接新建一个类来复用
<?php
namespace App\Queries;
use App\Models\Article;
use Illuminate\Contracts\Pagination\Paginator;
final class SearchArticles
{
/**
* @return \App\Models\Article[]
*/
public static function get(string $keyword, int $perPage = 20): Paginator
{
return Article::where('title', 'like', "%$keyword%")
->orWhere('body', 'like', "%$keyword%")
->orWhere('slug', 'like', "%$keyword%")
->paginate($perPage);
}
}
留坑
测试 tests 个人感觉非常重要,可以非常快速寻找问题并解决bug,同时在编写测试的同时,以帮助自己更加清晰的梳理逻辑
缓存 cache 提高项目性能