站長資訊網(wǎng)
最全最豐富的資訊網(wǎng)站

Laravel中怎么實(shí)現(xiàn)Repository設(shè)計(jì)模式

Laravel中怎么實(shí)現(xiàn)Repository設(shè)計(jì)模式

Laravel 9 保姆級視頻教程,想學(xué)不會都難!進(jìn)入學(xué)習(xí)

在本文中,我會向你展示如何在 Laravel 中從頭開始實(shí)現(xiàn) repository 設(shè)計(jì)模式。我將使用 Laravel 5.8.3 版,但 Laravel 版本不是最重要的。在開始寫代碼之前,你需要了解一些關(guān)于 repository 設(shè)計(jì)模式的相關(guān)信息。

Laravel中怎么實(shí)現(xiàn)Repository設(shè)計(jì)模式

repository 設(shè)計(jì)模式允許你使用對象,而不需要了解這些對象是如何持久化的。本質(zhì)上,它是數(shù)據(jù)層的抽象。

這意味著你的業(yè)務(wù)邏輯不需要了解如何檢索數(shù)據(jù)或數(shù)據(jù)源是什么,業(yè)務(wù)邏輯依賴于 repository 來檢索正確的數(shù)據(jù)。

關(guān)于這個(gè)模式,我看到有人將它誤解為 repository 被用來創(chuàng)建或更新數(shù)據(jù)。 這不是 repository 應(yīng)該做的,repository 不應(yīng)該創(chuàng)建或更新數(shù)據(jù),僅僅用于檢索數(shù)據(jù)。

理解透了吧?接下來一起寫代碼

既然我們從頭開始,那么我們先創(chuàng)建一個(gè)新的 Laravel 項(xiàng)目吧:

composer create-project --prefer-dist laravel/laravel repository
登錄后復(fù)制

對于本教程,我們將構(gòu)建一個(gè)小型的博客應(yīng)用。現(xiàn)在我們已經(jīng)創(chuàng)建好了一個(gè)新的 Laravel 項(xiàng)目,接下來應(yīng)該為它創(chuàng)建一個(gè)控制器和模型。

php artisan make:controller BlogController
登錄后復(fù)制

這將在 app/Http/Controllers 目錄中創(chuàng)建 BlogController

php artisan make:model Models/Blog -m
登錄后復(fù)制

提示:
-m 選項(xiàng)會創(chuàng)建一個(gè)對應(yīng)的數(shù)據(jù)庫遷移,你可以在 *database/migrations
目錄中找到所生成的遷移。*

現(xiàn)在你應(yīng)該能在 app/Models 目錄中找到剛生成的模型 Blog 了吧。這只是一種我喜歡的存放模型的方式。

現(xiàn)在我們有了控制器和模型,是時(shí)候看看我們創(chuàng)建的遷移文件了。除了默認(rèn)的 Laravel 時(shí)間戳字段外,我們的博客只需要 標(biāo)題、內(nèi)容用戶ID 字段。

<?php  use IlluminateSupportFacadesSchema; use IlluminateDatabaseSchemaBlueprint; use IlluminateDatabaseMigrationsMigration;  class CreateBlogsTable extends Migration {     public function up()     {         Schema::create('blogs', function (Blueprint $table) {             $table->bigIncrements('id');             $table->string('title');             $table->text('content');             $table->integer('user_id');             $table->timestamps();              $table->foreign('user_id')                   ->references('id')                   ->on('users');         });     }      public function down()     {         Schema::dropIfExists('blogs');     } }
登錄后復(fù)制

提示:
如果你使用的是 Laravel 5.8 以下的舊版本,請將

$table->bigIncrements('id');
登錄后復(fù)制

替換為:

$table->increments('id');
登錄后復(fù)制

設(shè)置數(shù)據(jù)庫

我將使用 MySQL 數(shù)據(jù)庫作為示例,第一步就是創(chuàng)建一個(gè)新的數(shù)據(jù)庫。

mysql -u root -p  create database laravel_repository;
登錄后復(fù)制

以上命令將會創(chuàng)建一個(gè)叫 laravel_repository 的新數(shù)據(jù)庫。接下來我們需要添加數(shù)據(jù)庫信息到 Laravel 根目錄的 .env 文件中。

DB_DATABASE=laravel_repositoryDB_USERNAME=rootDB_PASSWORD=secret
登錄后復(fù)制

當(dāng)你更新了 .env 文件后我們需要清空緩存:

php artisan config:clear
登錄后復(fù)制

登錄后復(fù)制

運(yùn)行遷移

現(xiàn)在我們已經(jīng)設(shè)置好了數(shù)據(jù)庫,可以開始運(yùn)行遷移了:

php artisan migrate
登錄后復(fù)制

這將會創(chuàng)建 blogs 表,包含了我們在遷移中聲明的 title , contentuser_id 字段。

實(shí)現(xiàn) repository 設(shè)計(jì)模式

一切就緒,我們現(xiàn)在可以開始實(shí)現(xiàn) repository 設(shè)計(jì)風(fēng)格了。我們將會在 app 目錄中創(chuàng)建 Repositories 目錄。我們將要創(chuàng)建的第二個(gè)目錄是 Interfaces 目錄,這個(gè)目錄位于 Repositories 目錄中。

Interfaces 文件中我們將創(chuàng)建一個(gè)包含兩個(gè)方法的 BlogRepositoryInterface 接口。

  • 返回所有博客文章的 all 方法

  • 返回特定用戶所有博客文章的 getByUser 方法

<?php  namespace AppRepositoriesInterfaces;  use AppUser;  interface BlogRepositoryInterface {     public function all();      public function getByUser(User $user); }
登錄后復(fù)制

我們需要創(chuàng)建的最后一個(gè)類是將要實(shí)現(xiàn) BlogRepositoryInterfaceBlogRepository ,我們會寫一個(gè)最簡單的實(shí)現(xiàn)方式。

<?php  namespace AppRepositories;  use AppModelsBlog; use AppUser; use AppRepositoriesInterfacesBlogRepositoryInterface;  class BlogRepository implements BlogRepositoryInterface {     public function all()     {         return Blog::all();     }      public function getByUser(User $user)     {         return Blog::where('user_id',$user->id)->get();     } }
登錄后復(fù)制

你的 Repositories 目錄應(yīng)該像這樣:

app/└── Repositories/     ├── BlogRepository.php     └── Interfaces/         └── BlogRepositoryInterface.php
登錄后復(fù)制

你現(xiàn)在已經(jīng)成功創(chuàng)建了一個(gè) repository 了。但是我們還沒有完成,是時(shí)候開始使用我們的 repository 了。

在控制器中使用 Repository

要開始使用 BlogRepository ,我們首先需要將其注入到 BlogController 。由于 Laravel 的依賴注入,我們很容易用另一個(gè)來替換它。這就是我們控制器的樣子:

<?php  namespace AppHttpControllers;   use AppRepositoriesInterfacesBlogRepositoryInterface; use AppUser;  class BlogController extends Controller {     private $blogRepository;      public function __construct(BlogRepositoryInterface $blogRepository)     {         $this->blogRepository = $blogRepository;     }      public function index()     {         $blogs = $this->blogRepository->all();          return view('blog')->withBlogs($blogs);     }      public function detail($id)     {         $user = User::find($id);         $blogs = $this->blogRepository->getByUser($user);          return view('blog')->withBlogs($blogs);     } }
登錄后復(fù)制

如你所見,控制器中的代碼很簡短,可讀性非常的高。不需要十行代碼就可以獲取到所需的數(shù)據(jù),多虧了 repository ,所有這些邏輯都可以在一行代碼中完成。這對單元測試也很好,因?yàn)?repository 的方法很容易復(fù)用。

repository 設(shè)計(jì)模式也使更改數(shù)據(jù)源變得更加容易。在這個(gè)例子中,我們使用 MySQL 數(shù)據(jù)庫來檢索我們的博客內(nèi)容。我們使用 Eloquent 來完成查詢數(shù)據(jù)庫操作。但是假設(shè)我們在某個(gè)網(wǎng)站上看到了一個(gè)很棒的博客 API,我們想使用這個(gè) API 作為數(shù)據(jù)源,我們所要做的就是重寫 BlogRepository 來調(diào)用這個(gè) API 替換 Eloquent

RepositoryServiceProvider

我們將注入 BlogController 中的 BlogRepository ,而不是注入 BlogController 中的 BlogRepositoryInterface ,然后讓服務(wù)容器決定將使用哪個(gè)存儲庫。這將在 AppServiceProviderboot 方法中實(shí)現(xiàn),但我更喜歡為此創(chuàng)建一個(gè)新的 provider 來保持整潔。

php artisan make:provider RepositoryServiceProvider
登錄后復(fù)制

我們?yōu)榇藙?chuàng)建一個(gè)新的 provider 的原因是,當(dāng)您的項(xiàng)目開始發(fā)展為大型項(xiàng)目時(shí),結(jié)構(gòu)會變得非常凌亂。設(shè)想一下,一個(gè)擁有 10 個(gè)以上模型的項(xiàng)目,每個(gè)模型都有自己的 repository ,你的 AppServiceProvider 可讀性將會大大降低。

我們的 RepositoryServiceProvider 會像下面這樣:

<?php  namespace AppProviders;  use AppRepositoriesBlogRepository; use AppRepositoriesInterfacesBlogRepositoryInterface; use IlluminateSupportServiceProvider;  class RepositoryServiceProvider extends ServiceProvider {     public function register()     {         $this->app->bind(             BlogRepositoryInterface::class,              BlogRepository::class         );     } }
登錄后復(fù)制

留意用另一個(gè) repository 替代 BlogRepository 是多么容易!

不要忘記添加 RepositoryServiceProviderconfig/app.php 文件的 providers 列表中。完成了這些后我們需要清空緩存:

'providers' => [   AppProvidersRepositoryServiceProvider::class ],
登錄后復(fù)制

php artisan config:clear
登錄后復(fù)制

登錄后復(fù)制

就是這樣

現(xiàn)在你已經(jīng)成功實(shí)現(xiàn)了 repository 設(shè)計(jì)模式,不是很難吧?

你可以選擇增加一些路由和視圖來拓展代碼,但本文將在這里結(jié)束,因?yàn)楸疚闹饕墙榻B repository 設(shè)計(jì)模式的。

如果你喜歡這篇文章,或者它幫助你實(shí)現(xiàn)了 repository 設(shè)計(jì)模式,請確保你也查看了我的其他文章。如果你有任何反饋、疑問,或希望我撰寫另一個(gè)有關(guān) Laravel 的主題,請隨時(shí)發(fā)表評論。

原文地址:https://itnext.io/repository-design-pattern-done-right-in-laravel-d177b5fa75d4

譯文地址:https://learnku.com/laravel/t/31798

贊(0)
分享到: 更多 (0)
網(wǎng)站地圖   滬ICP備18035694號-2    滬公網(wǎng)安備31011702889846號
亚洲欧洲久久精品| 亚洲精品美女久久777777| 日韩精品内射视频免费观看| 精品一区二区三区四区在线| 亚洲日韩乱码久久久久久| 在线亚洲精品视频| 97久久精品人妻人人搡人人玩| 99久久亚洲精品无码毛片| 国产精品露脸国语对白| 中文字幕一精品亚洲无线一区| freesexvideos精品老师毛多| 日韩AV高清在线观看| 日韩精品无码久久一区二区三| 2020年国产精品| 香蕉久久丫精品忘忧草产品| 热久久视久久精品18| 亚洲婷婷第一狠人综合精品| 亚洲精品国产啊女成拍色拍| 久久夜色精品国产噜噜亚洲AV| 久久精品免视看国产成人| 亚洲精品成人片在线观看精品字幕 | 国99精品无码一区二区三区| 2022国产成人精品视频人| 东北妇女精品BBWBBW| 99re8这里有精品热视频免费| 久久国产精品波多野结衣AV| 国产精品激情综合久久 | 亚洲av专区无码观看精品天堂| 美日韩一区二区三区| 国产精品亚洲精品日韩已满| 国内少妇人妻偷人精品xxx| 国内精品久久久久影院薰衣草| 丰满人妻熟妇乱又仑精品| 在线观看自拍少妇精品| 国产精品亚韩精品无码a在线| 久久国产乱子精品免费女| 久久精品国产999大香线焦| 久久99热成人精品国产| 99精品国产一区二区三区不卡| 精品无码日韩一区二区三区不卡 | 91精品视频在线|