1. 程式人生 > >Laravel中簡單使用Repository模式

Laravel中簡單使用Repository模式

什麼是Repository模式,laravel學院中用這樣一張圖來解釋

這裡寫圖片描述

其實將這個模式用在專案中就是為了將業務邏輯和具體的呼叫分開,建立一個倉庫來存放這些業務邏輯。那麼我們怎麼使用呢?

這裡寫圖片描述

建立Repository目錄來存放不同的業務邏輯
在Contracts中存放介面檔案,Eloquent中存放具體的實現方法

TestRepository.php

<?php

namespace App\Repository\Test\Eloquent;

use App\Repository\Test\Contracts\TestRepositoryInterface
; class TestRepository implements TestRepositoryInterface { public function test() { return 'this is test repository'; } }

TestController.php

<?php 

namespace App\Http\Controllers;

use App\Http\Requests;
use Illuminate\Http\Request;

class TestController extends Controller
{
public function test() { $test = app('Test'); $testInfo = $test->test(); echo $testInfo; } }

編寫服務提供者
執行php artisan make:provider RepositoryServiceProvider
編寫你自己的服務提供者
app\Providers\RepositoryServiceProvider.php註冊Test倉庫

    public function register()
    {
$this->registerTestRepository(); } public function provides() { $test = ['Test']; return array_merge($test); } private function registerTestRepository() { $this->app->singleton('Test', 'App\Repository\Test\Eloquent\TestRepository'); }

在app.php的providers陣列中新增我們的服務提供者

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

總結

通過這種方式我們可以將不同的業務邏輯分別建立一個倉庫用來存放具體的方法,而在controller層只管呼叫不用去管具體的實現,也減少了controller層總對資料庫的操作,使程式碼更加規範簡潔。