欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

laravel 中repository模式使用詳解

 更新時(shí)間:2022年02月15日 15:41:06   作者:烏木喂喂威 恩耶吞溫威 烏溫穆扁 歐薩斯  
這篇文章主要介紹了laravel repository模式使用,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

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

編碼過(guò)程當(dāng)中 解耦一直是個(gè)較為熱門(mén)的話題。 使用MVC設(shè)計(jì)模式開(kāi)發(fā)的時(shí)候,如果需要查詢(xún)數(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)文章

最新評(píng)論