LoginSignup
0
0

More than 1 year has passed since last update.

サービスクラスの作成設定(Laravel)

Last updated at Posted at 2023-04-05

初めに

Laravelのサービスクラスの設定をしましたので
備忘録、テンプレートとして残します。

環境

開発環境 バージョン
Laravel 10.1.5
PHP 8.2.3

実装前

今回は、HomeController.phpに着目していきます。
まずは、Serviceを紐付ける前のソースです。

HomeController.php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class HomeController extends Controller
{
    // コンストラクタ
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index(Request $request)
    {
        Log::debug(__FUNCTION__);

        return view('home');
    }
}

実装後

app配下にServicesディレクトリを作成します。

実装します。
実装後のソースコードになります。

HomeController.php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use App\Services\HomeService;

class HomeController extends Controller
{
    protected $service;

    // コンストラクタ
    public function __construct(HomeService $service)
    {
        $this->middleware('auth');

        // 初期設定
        $this->service = $service;
    }

    public function index(Request $request)
    {
        Log::debug(__FUNCTION__);

        $this->service->test();

        return view('home');
    }
}

HomeService.phpファイルを作成します。
実装します。

HomeService.php
namespace App\Services;

use Illuminate\Support\Facades\Log;
 
/**
 * HOMEサービスクラス
 *
 */
class HomeService
{
    // コンストラクタ
    public function __construct()
    {
        Log::debug(get_class($this));
    }

    public function test()
    {
        Log::debug(__FUNCTION__);
    }
}

気をつけるポイントとして、パスに注意してください。
例:App\Service ではなく App\Services
"s"をつけること

最後に

最後まで閲覧いただきありがとうございました。
ご意見、ご指摘ありましたら、コメントお願いいたします。

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