laravel 中repository模式使用詳解
什么是Repository模式,laravel學(xué)院中用這樣一張圖來(lái)解釋

編碼過(guò)程當(dāng)中 解耦一直是個(gè)較為熱門(mén)的話題。 使用MVC設(shè)計(jì)模式開(kāi)發(fā)的時(shí)候,如果需要查詢數(shù)據(jù)庫(kù)/操作數(shù)據(jù)庫(kù)的時(shí)候就得直接引用模型,調(diào)用模型。按照常規(guī)的調(diào)用方法直接以下所示,不使用Eloquent ORM就沒(méi)法操作數(shù)據(jù)庫(kù),那么就是ORM和這個(gè)控制器有著非常之大的耦合性。
$position = Position::createPosition($params); $position->users()->attach($userParams); $position->permissions()->attach($permissionParams);
控制器方面應(yīng)該是只有返回相關(guān)的 不會(huì)包含任何邏輯的代碼,所以為了解耦我們就該引用repository設(shè)計(jì)模式。
repository 需要的開(kāi)發(fā)層面
首先我們需要定義一個(gè)接口
<?php
namespace App\Http\Repositories\Interfaces;
use App\Http\Repositories\Interfaces\BaseRepositoryInterface;
interface UserRepositoryInterface extends BaseRepositoryInterface
{
}可以自己先構(gòu)造一個(gè)基層的BaseInterface來(lái)封裝常用并且基本的操作模型的方法,創(chuàng)建好接口之后開(kāi)始綁定repository來(lái)進(jìn)行實(shí)現(xiàn)該接口
<?php
namespace App\Http\Permission\Repositories\Eloquent;
use App\Http\Repositories\Eloquent\EloquentBaseRepository;
use App\Http\Permission\Repositories\Interfaces\UserRepositoryInterface;
class UserRepository extends EloquentBaseRepository implements UserRepositoryInterface
{
}創(chuàng)建好之后需要在ServiceProvider當(dāng)中注冊(cè)并綁定該接口,保證與模型層有相關(guān)聯(lián)。
$this->app->bind(UserRepositoryInterface::class,function (){
return new UserRepository(new User);
});綁定好之后就可以創(chuàng)建service之后使用構(gòu)造函數(shù)來(lái)將該interface注入到其中 就可以書(shū)寫(xiě)邏輯以及相關(guān)編碼了。
到此這篇關(guān)于laravel repository模式使用的文章就介紹到這了,更多相關(guān)laravel repository模式內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
PHP時(shí)間戳與日期之間轉(zhuǎn)換的實(shí)例介紹
本篇文章小編為大家介紹,PHP時(shí)間戳與日期之間轉(zhuǎn)換的實(shí)例介紹。需要的朋友參考下2013-04-04
在Laravel框架里實(shí)現(xiàn)發(fā)送郵件實(shí)例(郵箱驗(yàn)證)
這篇文章主要介紹了在Laravel框架里實(shí)現(xiàn)發(fā)送郵件(郵箱驗(yàn)證)的相關(guān)資料,需要的朋友可以參考下2016-05-05
laravel5使用freetds連接sql server的方法
這篇文章主要給大家介紹了關(guān)于laravel5使用freetds連接sql server的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2018-12-12
ThinkPHP中的關(guān)聯(lián)模型注意點(diǎn)
這篇文章主要介紹了初學(xué)ThinkPHP中的關(guān)聯(lián)模型注意點(diǎn),需要的朋友可以參考下2014-06-06
yii2 modal彈窗之ActiveForm ajax表單異步驗(yàn)證
這篇文章主要介紹了yii2 modal彈窗之ActiveForm ajax表單驗(yàn)證的相關(guān)資料,非常不錯(cuò)具有參考借鑒價(jià)值,需要的朋友可以參考下2016-06-06
Yii2 rbac權(quán)限控制操作步驟實(shí)例教程
這篇文章主要介紹了Yii2 rbac權(quán)限控制操作步驟實(shí)例教程的相關(guān)資料,需要的朋友可以參考下2016-04-04

