- はじめ
開発の時、リポジトリを良く使うと思うが、有用だと思うのでリポジトリデザインパターンの紹介をします。 - Repositoryとは
データの操作に関連するロジックをビジネスロジックから切り離し、抽象化したレイヤに任せることで保守や拡張性を高めるパターンです。Laravelにリポジトリパターンを取り入れることで、
* テストがしやすくなる
* DBエンジンの変更に対応しやすくなる
* データ操作のロジックが1箇所にまとまり、管理しやすくなるといったメリットを得られる。 - LaravelにてRepository使う
Modelと同じ単位でリポジトリディレクトリを作成します。今回は以下のような構成でリポジトリパターンを実装していきます。
1234567├── Models│ ├── User.php│├── Repositories└── User├── UserRepository.php└── UserRepositoryInterface.php
でこれからデータ取得ロジックはモーデルじゃなくて、リポジトリで実装した方が良いと思う。
a. UserRepositoryInterface定義
123456namespace App\Repositories;interface UserRepositoryInterface{public function findByName($name);}
b. UserRepository実装
12345678910111213141516171819202122namespace App\Repositories\User;use App\Repositories\UserRepositoryInterface;use App\Models\User;class UserRepository implements UserRepositoryInterface{protected $user;/*** UserRepository constructor.* @param $user*/public function __construct($user){$this->user = $user;}public function findByName($name){return $this->user->where('name', '=', $name)->first();}}
c. AppServiceProviderに登録
123456789101112131415161718192021222324252627282930namespace App\Providers;use Illuminate\Support\ServiceProvider;class AppServiceProvider extends ServiceProvider{/*** Bootstrap any application services.** @return void*/public function boot(){//}/*** Register any application services.** @return void*/public function register(){// User$this->app->bind(\App\Repositories\User\UserRepositoryInterface::class,\App\Repositories\User\UserRepository::class);}}
d. コントロールで呼び出す
1234567891011121314151617namespace App\Http\Controller\User;use App\Repositories\User\UserRepositoryInterface;class UserController extends Controller{protected $userRepository;public function __construct(UserRepositoryInterface $userRepository){$this->userRepository = $userRepository;}public function index(){return $this->userRepository->findByName($name);}}
- まとめ
※基本的に、データロジックがあれば、リポジトリ使った方が良い。
※サーバー側じゃなくてアプリも同じ仕組みを使った方が良い。