首頁  >  文章  >  後端開發  >  Laravel Repository 模式

Laravel Repository 模式

WBOY
WBOY原創
2016-07-30 13:30:50901瀏覽

Repository 模式

為了保持程式碼的整潔性和可讀性,使用Repository Pattern 是非常有用的。事實上,我們也不必僅僅為了使用這個特別的設計模式去使用Laravel,然而在下面的場景下,我們將使用OOP的框架Laravel 去展示如何使用repositories 使我們的 去展示如何使用

層不再那麼囉嗦、更解耦、易讀。下面讓我們更深入的研究一下。

不使用 repositories

其實使用Repositories並不是必要的,在你的應用中你完全可以不使用這個設計模式的前提下完成絕大多數的事情,然而隨著時間的推移你可能把自己陷入一個死角,例如不選擇使用Repositories
會使你的應用測試很不容易,(swapping out implementations)具體的實作將會變的很複雜,下面我們來看一個例子。 HousesController.php

<?php
    class HousesController extends BaseController {
        public function index()
        {
            $houses = House::all();
            return View::make('houses.index',compact('houses'));
        }    
        
        public function create()
        {
            return View::make('houses.create');
        }
        public function show($id)
        {
            $house = House::find($id);
            return View::make('houses.show',compact('house'));
        }
    }

這是一個很典型的一段程式碼使用Eloquent和資料庫交互,這段程式碼工作的很正常,但是將雜的。在此我們可以注入一個repository建立一個解耦類型的程式碼版本,這個解耦的版本程式碼可以讓後續程式的具體實作更加簡單。 使用 repositories

其實完成整個repository

模式需要相當多的步驟,但是一旦你完成幾次就會自然而然變成了一種習慣了,下面我們將詳細介紹每一步。

1.創建 Repository

 資料夾

首先我們需要在app

資料夾建立自己

Repository 資料夾repositories,然後要設定資料夾對應的每個檔案都必須設定對應的命名空間。 2: 創建對應的 Interface

第二步創建對應的接口,其決定著我們的repository

類必須要實現的相關方法,如下例所示,在此再次強調的是命名空間一定要記得加上。

HouseRepositoryInterface.php
<pre class="brush:php;toolbar:false">&lt;?php namespace App\Repositories; interface HouseRepositoryInterface { public function selectAll(); public function find($id); } </pre>

3:創建對應的 

Repository

現在我們可以創建我們repository

現在我們可以創建我們repository
類來給我們做這個檔案多數的資料庫查詢都放進去,不論多麼複雜。如下面的例子DbHouseRepository.php

<?php namespace App\Repositories;

use House;

class DbHouseRepository implements HouseRepositoryInterface {
    
    public function selectAll()
    {
        return House::all();
    }

    public function find($id)
    {
        return House::find($id);
    }
}

<code><span><span> </span></span></code>

4:創建後端服務提供


首先你需要理解所謂服務提供,請參考手冊服務提供者

首先你需要理解所謂服務提供,請參考手冊服務提供者

🜎

當然你也可以新建一個資料夾主要放我們的

provider相關檔案。 上面一段程式碼主要說的是,當你在
controller層使用類型提示HouseRepositoryInterface,我們知道你將會使用DbHouseRepository.

5:更新你的
DbHouseRepository.
5:更新你的

。在程式碼中,我們已經實現了一個依賴注入,但如果我們要使用在此我們是需要手動去寫的,為了更為方面,我們需要增加這個providers 到app/config/app.php 中的 providers 數組裡面,只需要在最後加上AppRepositoriesBackendServiceProvider::class,

6:最後使用依賴注入更新你的controller

當我們完成上面的那些內容之後,我們在簡單的調用方法取代先前的複雜的資料庫調用,如下面內容:
HousesController.php

<?php namespace App\Repositories;

use IlluminateSupportSeriveProvider;

class BackSerivePrivider extends ServiceProvider {

    public function register()
    {
        $this->app->bind('App\Repositories\HouseRepositoryInterface', 'App\Repositories\DbHouseRepository');
    }
}

  這樣整個模式的轉換就完成了

以上就介紹了Laravel Repository 模式,包括了方面的內容,希望對PHP教程有興趣的朋友有所幫助。

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn