Home  >  Article  >  PHP Framework  >  Using Repository Pattern in laravel (warehouse mode)

Using Repository Pattern in laravel (warehouse mode)

藏色散人
藏色散人forward
2021-02-01 11:04:012872browse

The following tutorial column will introduce to you how to use Repository Pattern (warehouse mode) in laravel. I hope it will be helpful to friends in need! ##Article text

The main idea of ​​the Repository model is to build on a data operation proxy layer, which separates the data operations in the controller. The benefits of doing this are as follows: 1 Separating the data processing logic makes the code easier to maintain

2 Separating the data processing logic and business logic, you can test the two codes separately

3 Reduce code duplication

4 Reduce the probability of code errors

5 Greatly improve the readability of the controller code

As shown in the picture Show the hierarchical relationship of Repository

However, if you want to have an independent operation layer, it will add a lot of code, which is very cumbersome. If you have a small project, you may not need to use this mode. But if it is a complex and large-scale project lasting more than 4-5 years, the benefits of this model are more obvious.

The significance of learning Repository Pattern is not only to use it, but also to make you think deeply about the layered thinking of the framework. You will not only start to pay attention to how to use a framework, but also want to know how to design a framework. Maybe you will become Your entrance to advanced programming. When you realize what a thought is. . . Using Repository Pattern in laravel (warehouse mode)


Repository Pattern

Although the design pattern has nothing to do with the language and framework, it is separated from the language and framework. It is difficult for us to understand, so we still learn it in the context of laravel.
public function index(){

    $posts = Post::whereIn('category_id',[1,2])
        ->where('is_draft',0)
        ->orderBy('created_at', 'desc')
        ->take(5)
        ->get();

    return view('front.index',compact('posts'));}
The above is a typical Eloquent data query code. If you have rich programming experience, you will find that this kind of code is everywhere in the controller, and a lot of it is repeated and has poor readability; we The goal is to streamline it:

Look carefully

Post::whereIn('category_id',[1,2])->where('is_draft',0)->orderBy('created_at', 'desc')->take(5)->get();
In fact, it consists of 3 parts.

The first is the

Post

data model;

The second one is

whereIn('category_id',[1,2])->where('is_draft',0)->orderBy('created_at', 'desc')-> take(5), data operation conditions;

The third one is

get()method of data acquisition;

We know,

Eloquent# There is a Query Scope in ##, which can be used to simplify the second part, which is the query condition. So, after using

Query Scope

, we can simplify it to: <pre class="brush:php;toolbar:false">Post::ofCategory([1,2])-&gt;isDraft()-&gt;orderBy('created_at', 'desc')-&gt;take(5)-&gt;get();</pre> At first glance, it doesn’t seem to be very streamlined, but in fact you have achieved code decoupling and After reuse, for example isDraft(), this code can be used everywhere without worrying about coupling issues. The degree of simplification is related to the degree of abstraction of your logic. For example, you can write:

Post::findPosts([1,2],0,'desc',5)->get();

In light projects, it is highly recommended to use Query Scope. This is a good programming habits.

In more complex projects,

Query Scope

is not enough because it is still strongly coupled with the data model. Repository Pattern is to make the first , the second and third parts are all decoupled;

Speaking of decoupling, we have mentioned in Laravel’s document guide that the first artifact is the interface in PHP ( Interface

Let’s look at the exampleThe first step is to create a folder

app
Repositories
Interfaces
Implements

Interfaces is used to put interfaces, and Implements is used to Put the implementation of the interface;The second step is to create an interface

Create a new file in the above

Interfaces

directory

PostInterface.php

:

namespace App\Repositories\Interfaces;Interface PostInterface{   
    public function findPosts(Array $cat_id,$is_draft,$order,$take)   {

    }}

The third step is to create an implementation corresponding to the interfaceCreate a new file in the above Implements directory

PostRepository.php

:

namespace App\Repositories\Implements;use Post;class PostRepository Implements PostInterface{    
    public function findPosts(Array $cat_id,$is_draft,$order,$take){        
        $query = Post::whereIn('category_id',$cat_id)        
            ->where('is_draft',$is_draft)        
            ->orderBy('created_at', $order)        
            ->take($take)        
            ->get();        

        return $query;    
    }}

Obviously, the warehouse refers to the implementation of a warehouse interface; define your business logic here; The fourth step is to bind the interface in the ServiceProviderOpen

app/Providers/AppServiceProvider

, add code in

register()

:

<?php namespace App\Providers;use Illuminate\Support\ServiceProvider;class AppServiceProvider extends ServiceProvider{    
    public function boot(){ 

    }    

    public function register(){ 

        $this->app->bind('App\Repositories\Interfaces\PostInterface', 'App\Repositories\Implements\PostRepository');    
    }}

We know that ServiceProvider is where the Laravel IOC container implements dynamic interface change, so we bind it here, so that we When using it, do not use the interface implementation directly, but use the ioc container to parse the interface, which will automatically find the corresponding implementation for you. This means that if you need to change the implementation in the future, you can change it here;The fifth step is to use the warehouseReturn to our controller

use App\Repositories\Interfaces\PostInterface;class PostController extends BaseController{    
    public function __construct(PostInterface $post){ 

        $this->postRepo = $post;    
    }    

    public function index(){ 

        $this->postRepo->findPosts([1,2],0,'desc',5);    
    }}

从上面的例子看,我们的业务逻辑变得非常精简,完全不用管查询;而且也现实了数据查询部分的解耦。

The above is the detailed content of Using Repository Pattern in laravel (warehouse mode). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:learnku.com. If there is any infringement, please contact admin@php.cn delete