search
HomePHP FrameworkLaravelTeach you how to apply the Repository design pattern in Laravel5.8

The following tutorial column will introduce to you how to correctly apply the Repository design pattern in Laravel 5.8. I hope it will be helpful to friends in need!

In this article, I will show you how to implement the

repositoryTeach you how to apply the Repository design pattern in Laravel5.8 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.

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

php artisan make:controller BlogController

This will create the

BlogController

in the

app/Http/Controllers

directory.

php artisan make:model Models/Blog -m
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;);
    }}
Tips: If you are using an old version below Laravel 5.8, please replace

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

with:

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

Set up the database

mysql -u root -p 
create database laravel_repository;

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
After you update the .env file we need to clear the cache:

php artisan config:clear

Run the migration

blogs

table, which contains the

title

, we declared in the migration. content and user_id fields. Implementation

repositoryRepositories

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
  1. Returns the getByUser method of all blog posts of a specific user
  2. <?php
    
    namespace App\Repositories\Interfaces;use App\User;interface BlogRepositoryInterface{
        public function all();
    
        public function getByUser(User $user);}
    The last class we need to create is BlogRepository
  3. that will implement
BlogRepositoryInterface

, and 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();
    }}
Your Repositories directory should look like this:

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

You have now successfully created a repository. But we're not done yet, it's time to start using our

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 的主题,请随时发表评论。

The above is the detailed content of Teach you how to apply the Repository design pattern in Laravel5.8. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:learnku. If there is any infringement, please contact admin@php.cn delete
Laravel's Primary Function: Backend DevelopmentLaravel's Primary Function: Backend DevelopmentApr 15, 2025 am 12:14 AM

Laravel's core functions in back-end development include routing system, EloquentORM, migration function, cache system and queue system. 1. The routing system simplifies URL mapping and improves code organization and maintenance. 2.EloquentORM provides object-oriented data operations to improve development efficiency. 3. The migration function manages the database structure through version control to ensure consistency. 4. The cache system reduces database queries and improves response speed. 5. The queue system effectively processes large-scale data, avoid blocking user requests, and improve overall performance.

Laravel's Backend Capabilities: Databases, Logic, and MoreLaravel's Backend Capabilities: Databases, Logic, and MoreApr 14, 2025 am 12:04 AM

Laravel performs strongly in back-end development, simplifying database operations through EloquentORM, controllers and service classes handle business logic, and providing queues, events and other functions. 1) EloquentORM maps database tables through the model to simplify query. 2) Business logic is processed in controllers and service classes to improve modularity and maintainability. 3) Other functions such as queue systems help to handle complex needs.

Laravel's Versatility: From Simple Sites to Complex SystemsLaravel's Versatility: From Simple Sites to Complex SystemsApr 13, 2025 am 12:13 AM

The Laravel development project was chosen because of its flexibility and power to suit the needs of different sizes and complexities. Laravel provides routing system, EloquentORM, Artisan command line and other functions, supporting the development of from simple blogs to complex enterprise-level systems.

Laravel (PHP) vs. Python: Development Environments and EcosystemsLaravel (PHP) vs. Python: Development Environments and EcosystemsApr 12, 2025 am 12:10 AM

The comparison between Laravel and Python in the development environment and ecosystem is as follows: 1. The development environment of Laravel is simple, only PHP and Composer are required. It provides a rich range of extension packages such as LaravelForge, but the extension package maintenance may not be timely. 2. The development environment of Python is also simple, only Python and pip are required. The ecosystem is huge and covers multiple fields, but version and dependency management may be complex.

Laravel and the Backend: Powering Web Application LogicLaravel and the Backend: Powering Web Application LogicApr 11, 2025 am 11:29 AM

How does Laravel play a role in backend logic? It simplifies and enhances backend development through routing systems, EloquentORM, authentication and authorization, event and listeners, and performance optimization. 1. The routing system allows the definition of URL structure and request processing logic. 2.EloquentORM simplifies database interaction. 3. The authentication and authorization system is convenient for user management. 4. The event and listener implement loosely coupled code structure. 5. Performance optimization improves application efficiency through caching and queueing.

Why is Laravel so popular?Why is Laravel so popular?Apr 02, 2025 pm 02:16 PM

Laravel's popularity includes its simplified development process, providing a pleasant development environment, and rich features. 1) It absorbs the design philosophy of RubyonRails, combining the flexibility of PHP. 2) Provide tools such as EloquentORM, Blade template engine, etc. to improve development efficiency. 3) Its MVC architecture and dependency injection mechanism make the code more modular and testable. 4) Provides powerful debugging tools and performance optimization methods such as caching systems and best practices.

Which is better, Django or Laravel?Which is better, Django or Laravel?Mar 28, 2025 am 10:41 AM

Both Django and Laravel are full-stack frameworks. Django is suitable for Python developers and complex business logic, while Laravel is suitable for PHP developers and elegant syntax. 1.Django is based on Python and follows the "battery-complete" philosophy, suitable for rapid development and high concurrency. 2.Laravel is based on PHP, emphasizing the developer experience, and is suitable for small to medium-sized projects.

Which is better PHP or Laravel?Which is better PHP or Laravel?Mar 27, 2025 pm 05:31 PM

PHP and Laravel are not directly comparable, because Laravel is a PHP-based framework. 1.PHP is suitable for small projects or rapid prototyping because it is simple and direct. 2. Laravel is suitable for large projects or efficient development because it provides rich functions and tools, but has a steep learning curve and may not be as good as pure PHP.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment