LoginSignup
9
11

More than 3 years have passed since last update.

Service層を意識したLaravelのMVCモデル(実践編)

Posted at

はじめに

前回Service層を意識したLaravelのMVCモデル(概念編)についてまとめたので、こちらも参考にしていただければと思います。
前回は仕組みについてまとめたので今回は実際にどんな感じにコーディングするのかまとめてみました。

実際にコードを覗いてみましょう

今回はDBに登録済みのユーザーデータを取得し一覧画面に表示するというコーディングをします。

コントローラ層:必要な情報を整理して画面表示や処理を指示する

UserController.php
<?php
namespace App\Http\Controllers;

use App\Services\UserService;
use Illuminate\Support\Facades\DB;
use Illuminate\View\View;

/**
 * ユーザーに関するコントローラークラス
 * @package App\Http\Controllers
 */
class UserController extends Controller
{
    /**
     * ユーザー一覧画面表示
     * @return ユーザー一覧
     */
    public function index() :View
    {
        $users = UserService::getUsers();
        return view('user.index', compact('users'));
    }
}

サービス層:取得したデータの並び替えなどの加工をする

UserService.php
<?php
namespace App\Services;

use App\Models\User;
use Illuminate\Database\Eloquent\Collection;

/**
 * ユーザー情報のサービスクラス
 * @package App\Services
 */
class UserService
{
    /**
     * 全ユーザー情報取得
     * @return Collection 全ユーザー情報
     */
    public static function getUsers(): Collection
    {
        return User::getUsers();
    }
}

モデル層:データを取得するなどDBの操作をする

User.php
<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Collection;

/**
 * ユーザーテーブルのモデルクラス
 * @package App\Models
 */
class User extends BaseModel
{
    /**
     * 全ユーザー情報取得
     * @return Collection 全ユーザー情報
     */
    public static function getUsers(): Collection
    {
        return self::all();
    }

おわりに

今回は簡潔にまとめるために並び替えや取得するデータの指定などはしませんでしたが、ぜひ試してみてください。

9
11
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
9
11