0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

laravelでService Repositoryの概念で実装してみた感想

0
Posted at

結論

SeriviceとRepositoryのlaravelへの導入方法は
いろんなサイトで紹介されているので、それぞれ試してみましたが
自分自身でコーディングしてみた感想としては
laravelのeloquentを使いたいならrepositoryは不要な気がします。
大規模なDBとかの経験がないだけなのかもしれないが。

Repositoryの導入途中で「あれ?リレーションはどうすんだ?」
「eager loadingつかえんのか?」とみていくと
withとかwithTrashedとか自前で実装しないといけないことに気づいた。

laravelのリレーションとかeager loadingとかの便利機能を使いつつ
SQL文を直接クエリで書きたいくらいのレベルでは
Repositoryは機能が重すぎる。

以下で十分。ViewはInertiajsを想定。

Controller

requestのバリデーションとresponseの行先のみ指定。

Controller.php
private: $someService;
public function __construct(SomeServiceInterface $someService)
{
    $this->someService = $someService;
}
public function store(StoreRequest $request)
{
    try {
        $this->someService->create($request->all());
        return redirect()->route('posts.index')->with(['message' => '追加しました。']);
    } catch (Throwable $e) {
        return redirect()->back()->with(['error' => $error_message]);
    }
}

Service

業務処理の実体。
interfaceは型を厳密にしたいときやメソッドの公開を限定的にしたい場合。

app/Services/SomeService.php
class SomeService implements SomeServiceInterface
{
    public function create(array $data): ?Model
    {
        DB::beginTransaction();
        try {
            $post = new Post($data);
            $post->save();
            DB::commit();
            return $post;
        } catch(Throwable $e) {
            DB::rollBack();
            return null;
        }
    }
}

Model

DBのテーブルのラッパー。
laravelのeloquentの便利機能を使いたいならこれで十分。

View

応答データ。webならblade、vue、react。apiならjson。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?