Table of Contents
Setting up the database" >Setting up the database
Run migration" >Run migration
##Implementationrepository Design patternEverything is ready, we can now start to implement the " >##Implementationrepository Design patternEverything is ready, we can now start to implement the
To start using BlogRepository, we first need to Inject it into " >Repository in a ControllerTo start using BlogRepository, we first need to Inject it into
RepositoryServiceProvider" >RepositoryServiceProvider
Home PHP Framework Laravel How to implement the Repository design pattern in Laravel

How to implement the Repository design pattern in Laravel

Nov 08, 2022 pm 08:39 PM
php laravel

How to implement the Repository design pattern in Laravel

In this article, I will show you how to implement the repository design pattern from scratch in Laravel. I will be using Laravel version 5.8.3, but Laravel version is not the most important. Before you start writing code, you need to know some information about repository design patterns.

How to implement the Repository design pattern in Laravel

repository Design patterns allow you to work with objects without knowing how those objects are persisted. Essentially, it is an abstraction of the data layer.

This means that your business logic does not need to know how to retrieve the data or what the data source is, the business logic relies on the repository to retrieve the correct data.

Regarding this pattern, I have seen some misunderstanding it as repository being used to create or update data. This is not what repository is supposed to do, repository is not supposed to create or update data, only to retrieve it.

Do you understand? Let’s write the code together

Since we are starting from scratch, let’s create a new Laravel project:

composer create-project --prefer-dist laravel/laravel repository
Copy after login

For this tutorial, we will build a small blogging application. Now that we have created a new Laravel project, we should create a controller and model for it.

php artisan make:controller BlogController
Copy after login

This will create the BlogController in the app/Http/Controllers directory.

php artisan make:model Models/Blog -m
Copy after login

Tip: The
-m option will create a corresponding database migration. You can find the generated migration in the *database/migrations
directory. *

Now you should be able to find the newly generated model Blog in the app/Models directory. This is just a way I like to store my models.

Now that we have our controller and model, it’s time to look at the migration file we created. In addition to the default Laravel timestamp fields, our blog only requires the Title, Content, and UserID fields.

<?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;);
    }
}
Copy after login

Tips:
If you are using an old version below Laravel 5.8, please replace

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

with:

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

I will use the MySQL database as an example, the first step is to create a new database.

mysql -u root -p 
create database laravel_repository;
Copy after login

The above command will create a new database called laravel_repository. Next we need to add database information to the .env file in the Laravel root directory.

DB_DATABASE=laravel_repositoryDB_USERNAME=rootDB_PASSWORD=secret
Copy after login

We need to clear the cache after you update the .env file:

php artisan config:clear
Copy after login
Copy after login

Now that we have the database set up, we can start running the migration:

php artisan migrate
Copy after login

This will create the blogs table, containing the title# we declared in the migration ## , content and user_id fields.

repository

design Styled. We will create the Repositories directory inside the app directory. The second directory we will create is the Interfaces directory, which is located within the Repositories directory. In the

Interfaces

file we will create a BlogRepositoryInterface interface that contains two methods.

    Returns the
  • all

    method of all blog posts

  • Returns the
  • getByUser## of all the blog posts of a specific user # Method

    <?php
    
    namespace App\Repositories\Interfaces;
    
    use App\User;
    
    interface BlogRepositoryInterface
    {
        public function all();
    
        public function getByUser(User $user);
    }
    Copy after login

    The last class we need to create is
  • BlogRepository
that will implement

BlogRepositoryInterface, we will write the simplest implementation .

<?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();
    }
}
Copy after login
Your Repositories

directory should look like this:

app/└── Repositories/
    ├── BlogRepository.php
    └── Interfaces/
        └── BlogRepositoryInterface.php
Copy after login
You have now successfully created a repository

. But we're not done yet, it's time to start using our

repository.

##Using BlogController

. Thanks to Laravel's dependency injection, we can easily replace it with another one. This is what our controller looks like:

<?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);
    }
}
Copy after login
As you can see, the code in the controller is very short and very readable. It doesn’t take ten lines of code to get the data you need, thanks to repository all this logic can be done in one line of code. This is also great for unit testing because the

repository

methods are easily reusable.

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

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

php artisan make:provider RepositoryServiceProvider
Copy after login

我们为此创建一个新的 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
        );
    }
}
Copy after login

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

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

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

就是这样

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

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

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

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

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

【相关推荐:laravel视频教程

The above is the detailed content of How to implement the Repository design pattern in Laravel. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP's Purpose: Building Dynamic Websites PHP's Purpose: Building Dynamic Websites Apr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Why Use PHP? Advantages and Benefits Explained Why Use PHP? Advantages and Benefits Explained Apr 16, 2025 am 12:16 AM

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP: An Introduction to the Server-Side Scripting Language PHP: An Introduction to the Server-Side Scripting Language Apr 16, 2025 am 12:18 AM

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

PHP and the Web: Exploring its Long-Term Impact PHP and the Web: Exploring its Long-Term Impact Apr 16, 2025 am 12:17 AM

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.

See all articles