LoginSignup
46
36

More than 1 year has passed since last update.

Laravel でサービス(Service)クラスの作り方

Last updated at Posted at 2020-05-03

やりたいこと

Request→Controller→Service→Model or Repository
のようにビジネスロジックの処理箇所としてServiceクラスを作成する

やりかた

app配下にServicesディレクトリ作成

HogeService.php(名称は何でもいい)を作成

app/Services/HogeService.php
<?php

namespace App\Services;

class HogeService
{
    public function hoge()
    {
          echo 'hoge';
    }
}

あとはControllerで呼び出すだけ
コンストラクタインジェクションまたは、メソッドインジェクションします

HogeController
<?php

namespace App\Http\Controllers;

use App\Services\HogeService;

class HogeController extends Controller
{
    private $hoge;
    public function __construct(HogeService $hoge_service)
    {
        $this->hoge = $hoge_service
    }

    public function index(HogeService $hoge_service)
    {
        $this->hoge->hoge();
        $hoge_service->hoge()
    }
}

AppserviceProviderに記載する手順の記事が出たりしますが
公式または翻訳の通り、基本的には書かなくても問題ないです。
インターフェースをDIしたりする際には必要です。

スクリーンショット 2020-05-03 22.46.14.png

https://qiita.com/minechan1234/items/2cc7c69875fafb2fdae9
https://qiita.com/ekzemplaro/items/354166c8612e45dbe822

46
36
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
46
36