第14回 Laravel10 環境構築メモ(Repository パターンを使ってみる)

はじめに

前回、登録画面を少しアップグレードさせたのですが、今回は更なるアップグレードという事でレポジトリパターンを使ってみようと思います。レポジトリパターンはググれば沢山説明でてくるものです。
次にテストコードを書こうと思ったのですが、Mockを使いたくて、その為だけに今回、レポジトリパターンを採用してみました。

ちなみに今回はdocはcopilotに書いてもらいました。

Interfaceを作成

  • app/Repositories/Greeting/GreetingRepository.php

<?php

namespace App\Repositories\Greeting;
use App\Models\Greeting;

/**
 * Interface GreetingRepositoryInterface
 *
 * This interface declares the methods that a GreetingRepository should implement.
 * It provides a contract that any class implementing this interface must fulfill.
 * Currently, it declares a single method `create` which is expected to create a new Greeting.
 */
interface GreetingRepositoryInterface
{
    /**
     * Create a new Greeting.
     *
     * This method accepts an array of greeting data and is expected to create a new Greeting.
     * It should return the newly created Greeting instance.
     *
     * @param array $greeting - An array of greeting data.
     * @return Greeting - The newly created Greeting instance.
     */
    public function create(array $greeting): Greeting;
}

Repositoryを作成

  • app/Repositories/Greeting/GreetingRepository.php

<?php
namespace App\Repositories\Greeting;

use App\Models\Greeting;

/**
 * Class GreetingRepository
 *
 * This class implements the GreetingRepositoryInterface.
 * It provides a concrete implementation of the methods declared in the interface.
 * It uses the Greeting model to interact with the database.
 */
class GreetingRepository implements GreetingRepositoryInterface
{
    /**
     * Create a new Greeting.
     *
     * This method accepts an array of greeting data and uses the Greeting model to create a new Greeting in the database.
     * It returns the newly created Greeting instance.
     *
     * @param array $greeting - An array of greeting data.
     * @return Greeting - The newly created Greeting instance.
     */
    public function create(array $greeting): Greeting
    {
        return Greeting::create($greeting);
    }
}

Providerに登録

  • app/Providers/AppServiceProvider.php

<?php

namespace App\Providers;

use App\Repositories\Greeting\GreetingRepository;
use App\Repositories\Greeting\GreetingRepositoryInterface;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     */
    public function register(): void
    {
        $this->app->bind(
            GreetingRepositoryInterface::class,
            GreetingRepository::class
        );
    }

    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        //
    }
}

Contorollerを修正

修正した部分だけ記載しています。

  • app/Http/Controllers/GreetingController.php

<?php

namespace App\Http\Controllers;

use App\Http\Requests\Greeting\StoreRequest;
use App\Http\Resources\GreetingResource;
use App\Models\Greeting;
use App\Repositories\Greeting\GreetingRepositoryInterface;
use Inertia\Inertia;

class GreetingController extends Controller
{
    /**
     * @var GreetingRepositoryInterface
     *
     * This property holds an instance of GreetingRepositoryInterface.
     * It is used to interact with the data layer of the application, specifically with Greeting resources.
     * It is injected via the constructor of this class.
     */
    protected GreetingRepositoryInterface $greetingRepository;

    /**
     * @var GreetingRepositoryInterface
     *
     * This property holds an instance of GreetingRepositoryInterface.
     * It is used to interact with the data layer of the application, specifically with Greeting resources.
     * It is injected via the constructor of this class.
     */
    public function __construct(
        GreetingRepositoryInterface $greetingRepository,
    )
    {
        $this->greetingRepository = $greetingRepository;
    }

   /** 省略 **/

    /**
     * Store a newly created resource in storage.
     *
     * This method is responsible for creating a new Greeting.
     * It accepts a StoreRequest instance which validates the incoming request data.
     * It then uses the GreetingRepositoryInterface to create a new Greeting in the database.
     * If the creation is successful, it redirects the user to the index page with a success message.
     * If an exception occurs during the creation, it redirects the user back to the form with an error message.
     *
     * @param StoreRequest $request - An instance of StoreRequest which validates the incoming request data.
     * @return \Illuminate\Http\RedirectResponse
     * @throws \Exception
     */
    public function store(StoreRequest $request)
    {
        try {
            $greeting = $request->only(['country', 'message',]);
            $this->greetingRepository->create($greeting);
            return to_route('greetings.index')->with('flash', 'Greeting created successfully');
        } catch (\Exception $e) {
            return back()->with('flash', 'Something went wrong');
        }
    }

   /** 省略 **/

}

今回は以上です。動きは全く変わりません。


いいなと思ったら応援しよう!