1. 程式人生 > >Laravel Repository 倉庫模式實踐

Laravel Repository 倉庫模式實踐

1 新建倉庫目錄

app/Repository                       # 倉庫目錄
  |--app/Repository/Interfaces       # 倉庫介面定義
|--app/Repository/Repositories # 倉庫介面實現

2 定義介面

# app/Repository/Interfaces/TestInterface.php

namespace App\Repository\Interfaces;

Interface TestInterface
{
    public function all();
}

3 介面實現

# app/Repository/Repositories/TestRepository.php

namespace App\Repository\Repositories;


use App\Repository
\Interfaces\TestInterface; class TestRepository Implements TestInterface { public function all() { // TODO: Implement findPosts() method. return ['all']; } }

4 介面繫結實現

4.1 建立一個服務

php artisan make:provider RepositoryServiceProvider

命令執行後會在 app/Providers 下建立 RepositoryServiceProvider.php 服務

4.2 將服務配置到應用中

app/config/app.php 中配置

'providers' => [
    ...
    App\Providers\RepositoryServiceProvider::class,
]

4.3 繫結介面

# app/Providers/RepositoryServiceProvider.php

/**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind('App\Repository\Interfaces\TestInterface', 'App\Repository\Repositories\TestRepository');
    }

5 倉庫呼叫

5.1 建立控制器

 php artisan make:controller TestController

命令執行後會在 app/Http/Controllers 下生成 TestController.php

5.2 呼叫實現

# app/Http/Controllers/TestController.php

<?php

namespace App\Http\Controllers;


use App\Repository\Interfaces\TestInterface;

class TestController extends Controller
{
    public $testRepo;

    public function __construct(TestInterface $test)
    {
        $this->testRepo = $test;
    }

    public function index()
    {
        $res = $this->testRepo->all();
        return $res;
    }
}

6 配置路由在瀏覽器中訪問

# app/routes/web.php

Route::get('test', '[email protected]');