首頁  >  文章  >  php框架  >  Laravel中怎麼實作Repository設計模式

Laravel中怎麼實作Repository設計模式

青灯夜游
青灯夜游轉載
2022-11-08 20:39:441580瀏覽

Laravel中怎麼實作Repository設計模式

在本文中,我會向你展示如何在 Laravel 中從頭開始實作 repository 設計模式。我將使用 Laravel 5.8.3 版,但 Laravel 版本不是最重要的。在開始寫程式碼之前,你需要了解一些關於 repository 設計模式的相關資訊。

Laravel中怎麼實作Repository設計模式

repository 設計模式讓你可以使用對象,而不需要了解這些物件是如何持久化的。本質上,它是資料層的抽象。

這意味著你的業務邏輯不需要了解如何檢索資料或資料來源是什麼,而業務邏輯依賴 repository 來檢索正確的資料。

關於這個模式,我看到有人將它誤解為 repository 被用來建立或更新資料。這不是 repository 應該做的,repository 不應該創建或更新數據,僅用於檢索數據。

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

既然我們從頭開始,那麼我們先創建一個新的 Laravel 專案吧:

composer create-project --prefer-dist laravel/laravel repository

對於本教程,我們將建立一個小型的部落格應用程式。現在我們已經創建好了一個新的 Laravel 項目,接下來應該為它建立一個控制器和模型。

php artisan make:controller BlogController

這將在 app/Http/Controllers 目錄中建立 BlogController

php artisan make:model Models/Blog -m

提示:
-m 選項會建立一個對應的資料庫遷移,你可以在  *database/migrations
目錄中找到所產生的遷移。 *

現在你應該可以在 app/Models 目錄中找到剛產生的模型 Blog 了吧。這只是一種我喜歡的存放模型的方式。

現在我們有了控制器和模型,是時候看看我們建立的遷移檔案了。除了預設的 Laravel 時間戳欄位外,我們的部落格只需要 標題、內容用戶ID 欄位。

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateBlogsTable extends Migration
{
    public function up()
    {
        Schema::create(&#39;blogs&#39;, function (Blueprint $table) {
            $table->bigIncrements(&#39;id&#39;);
            $table->string(&#39;title&#39;);
            $table->text(&#39;content&#39;);
            $table->integer(&#39;user_id&#39;);
            $table->timestamps();

            $table->foreign(&#39;user_id&#39;)
                  ->references(&#39;id&#39;)
                  ->on(&#39;users&#39;);
        });
    }

    public function down()
    {
        Schema::dropIfExists(&#39;blogs&#39;);
    }
}

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

$table->bigIncrements(&#39;id&#39;);

替換為:

$table->increments(&#39;id&#39;);

設定資料庫

我將使用MySQL 資料庫作為範例,第一步就是建立一個新的資料庫。

mysql -u root -p 
create database laravel_repository;

以上指令將會建立一個叫 laravel_repository 的新資料庫。接下來我們需要新增資料庫資訊到 Laravel 根目錄的 .env 檔案中。

DB_DATABASE=laravel_repositoryDB_USERNAME=rootDB_PASSWORD=secret

當你更新了.env 檔案後我們需要清空快取:

php artisan config:clear

##執行遷移

現在我們已經設定好了資料庫,可以開始執行遷移了:

php artisan migrate

這將會建立

blogs 表,包含了我們在遷移中宣告的title , contentuser_id 欄位。

實作repository 設計模式

#一切就緒,我們現在可以開始實作

repository 設計風格了。我們將會在 app 目錄中建立 Repositories 目錄。我們將要建立的第二個目錄是 Interfaces 目錄,這個目錄位於 Repositories 目錄中。

Interfaces 檔案中我們將建立一個包含兩個方法的 BlogRepositoryInterface 介面。

  • 傳回所有部落格文章的

    all 方法

  • #傳回特定使用者所有部落格文章的

    getByUser 方法

  • <?php
    
    namespace App\Repositories\Interfaces;
    
    use App\User;
    
    interface BlogRepositoryInterface
    {
        public function all();
    
        public function getByUser(User $user);
    }
我們需要建立的最後一個類別是將要實作

BlogRepositoryInterfaceBlogRepository  ,我們會寫一個最簡單的實作方式。

<?php

namespace App\Repositories;

use App\Models\Blog;
use App\User;
use App\Repositories\Interfaces\BlogRepositoryInterface;

class BlogRepository implements BlogRepositoryInterface
{
    public function all()
    {
        return Blog::all();
    }

    public function getByUser(User $user)
    {
        return Blog::where(&#39;user_id&#39;,$user->id)->get();
    }
}

你的

Repositories 目錄應該要這樣:

app/└── Repositories/
    ├── BlogRepository.php
    └── Interfaces/
        └── BlogRepositoryInterface.php

你現在已經成功建立了一個

repository 了。但我們還沒完成,是時候開始使用我們的 repository 了。

在控制器中使用Repository

#要開始使用

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

<?php

namespace App\Http\Controllers;


use App\Repositories\Interfaces\BlogRepositoryInterface;
use App\User;

class BlogController extends Controller
{
    private $blogRepository;

    public function __construct(BlogRepositoryInterface $blogRepository)
    {
        $this->blogRepository = $blogRepository;
    }

    public function index()
    {
        $blogs = $this->blogRepository->all();

        return view(&#39;blog&#39;)->withBlogs($blogs);
    }

    public function detail($id)
    {
        $user = User::find($id);
        $blogs = $this->blogRepository->getByUser($user);

        return view(&#39;blog&#39;)->withBlogs($blogs);
    }
}

如你所見,控制器中的程式碼很簡短,可讀性非常的高。不需要十行程式碼就可以獲得所需的數據,多虧了

repository ,所有這些邏輯都可以在一行程式碼中完成。這對單元測試也很好,因為 repository 的方法很容易重複使用。

repository 设计模式也使更改数据源变得更加容易。在这个例子中,我们使用 MySQL 数据库来检索我们的博客内容。我们使用 Eloquent 来完成查询数据库操作。但是假设我们在某个网站上看到了一个很棒的博客 API,我们想使用这个 API 作为数据源,我们所要做的就是重写 BlogRepository 来调用这个 API 替换 Eloquent

RepositoryServiceProvider

我们将注入 BlogController 中的 BlogRepository ,而不是注入 BlogController 中的 BlogRepositoryInterface ,然后让服务容器决定将使用哪个存储库。这将在 AppServiceProviderboot 方法中实现,但我更喜欢为此创建一个新的 provider 来保持整洁。

php artisan make:provider RepositoryServiceProvider

我们为此创建一个新的 provider 的原因是,当您的项目开始发展为大型项目时,结构会变得非常凌乱。设想一下,一个拥有 10 个以上模型的项目,每个模型都有自己的 repository ,你的 AppServiceProvider 可读性将会大大降低。

我们的 RepositoryServiceProvider 会像下面这样:

<?php

namespace App\Providers;

use App\Repositories\BlogRepository;
use App\Repositories\Interfaces\BlogRepositoryInterface;
use Illuminate\Support\ServiceProvider;

class RepositoryServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->bind(
            BlogRepositoryInterface::class, 
            BlogRepository::class
        );
    }
}

留意用另一个 repository 替代 BlogRepository 是多么容易!

不要忘记添加 RepositoryServiceProviderconfig/app.php 文件的 providers 列表中。完成了这些后我们需要清空缓存:

&#39;providers&#39; => [
  \App\Providers\RepositoryServiceProvider::class
],
php artisan config:clear

就是这样

现在你已经成功实现了 repository 设计模式,不是很难吧?

你可以选择增加一些路由和视图来拓展代码,但本文将在这里结束,因为本文主要是介绍 repository 设计模式的。

如果你喜欢这篇文章,或者它帮助你实现了 repository 设计模式,请确保你也查看了我的其他文章。如果你有任何反馈、疑问,或希望我撰写另一个有关 Laravel 的主题,请随时发表评论。

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

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

【相关推荐:laravel视频教程

以上是Laravel中怎麼實作Repository設計模式的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:learnku.com。如有侵權,請聯絡admin@php.cn刪除