search
HomeBackend DevelopmentPHP TutorialLaravel Repository pattern, laravelrepository_PHP tutorial

Laravel Repository mode, laravelrepository

Repository mode

To keep the code clean and readable, it is very useful to use Repository Pattern. In fact, we don’t have to use Laravel just to use this particular design pattern. However, in the following scenario, we will use the OOP framework Laravel to show how to use repositories to make our ControllerLayers are less verbose, more decoupled and more readable. Let’s take a closer look.

Do not use repositories

In fact, it is not necessary to use Repositories. You can complete most things in your application without using this design pattern. However, as time goes by, you may get yourself into a dead end. For example, if you don't choose to use Repositories, it will be very difficult to test your application. (Swapping out implementations) The specific implementation will become very complicated. Let's look at an example below.
HousesController.php

<?php
    class HousesController extends BaseController {
        public function index()
        {
            $houses = House::all();
            return View::make('houses.index',compact('houses'));
        }    
        
        public function create()
        {
            return View::make('houses.create');
        }
        public function show($id)
        {
            $house = House::find($id);
            return View::make('houses.show',compact('house'));
        }
    }

 

This is a typical piece of code that uses Eloquent to interact with the database. This code works normally, but the controller layer will be tightly coupled to Eloquent. Here we can inject a repository to create a decoupled version of the code. This decoupled version of the code can make the specific implementation of subsequent programs simpler.

Use repositories

Actually completing the entire repository mode requires quite a few steps, but once you complete it a few times it will naturally become a habit. Below we will introduce each step in detail.

1. Create Repository folder

First we need to create our own appfolderRepository  in the repositories folder, and then each file in the folder must set the corresponding namespace.

2: Create the corresponding Interfaceclass

The second step is to create the corresponding interface, which determines the relevant methods that our repository class must implement, as shown in the example below. It is emphasized again that the namespace must be added.
HouseRepositoryInterface.php

<?php namespace App\Repositories;

interface HouseRepositoryInterface {
    public function selectAll();
    
    public function find($id);
}

 

3: Create the corresponding Repository class

Now we can create our repository class to do the work for us. In this class file we can put most of our database queries, no matter how complex. As in the following example
DbHouseRepository.php

<?php namespace App\Repositories;

use House;

class DbHouseRepository implements HouseRepositoryInterface {
    
    public function selectAll()
    {
        return House::all();
    }

    public function find($id)
    {
        return House::find($id);
    }
}

 

<code><span class="php"><span class="hljs-preprocessor"> </span></span></code>

4: Create backend service provider

First you need to understand the so-called service provision, please refer to the manual service provider
BackendServiceProvider.php

<?php namespace App\Repositories;

use IlluminateSupportSeriveProvider;

class BackSerivePrivider extends ServiceProvider {

    public function register()
    {
        $this->app->bind('App\Repositories\HouseRepositoryInterface', 'App\Repositories\DbHouseRepository');
    }
}

 

<code><span class="php"><span class="hljs-preprocessor"> </span></span></code>

Of course, you can also create a new folder to mainly store our provider related files.
What the above code mainly says is that when you use type hints controller in the HouseRepositoryInterface layer, we know that you will use DbHouseRepository.

5: Update your Providers Array

In fact, in the above code, we have implemented a dependency injection, but if we want to use it here, we need to write it manually. For more convenience, we need to add this providers  to app/config/ In the providers array in app.php, just add AppRepositoriesBackendServiceProvider::class,

at the end

6: Finally update your controller

using dependency injection

After we complete the above content, we only need to simply call the method in Controller instead of the previous complex database call, as shown below:
HousesController.php

<?php 

use App\repositories\HouseRepositoryInterface;

class HousesController extends BaseController {
    protected $house;
    
    public function __construct(HouseRepositoryInterface $house)
    {
        $this->house = $house;
    }


    public function index()
    {
        $houses = $this->house->selectAll();

        return View::make('houses.index', compact('houses'));
        
    }


    public function create()
    {
        return View::make('houses.create');
    }


    public function show($id)
    {
        $house = $this->house->find($id);
        
        return View::make('houses.show', compact('house'));

    }
}

 

In this way, the entire mode conversion is completed

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1048733.htmlTechArticleLaravel Repository pattern, laravelrepository Repository pattern In order to keep the code clean and readable, it is very useful to use the Repository Pattern of. In fact, we don’t have to...
Statement
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
iBatis与MyBatis:比较与优势剖析iBatis与MyBatis:比较与优势剖析Feb 18, 2024 pm 01:53 PM

iBatis和MyBatis:区别和优势解析导语:在Java开发中,持久化是一个常见的需求,而iBatis和MyBatis是两个广泛使用的持久化框架。虽然它们有很多相似之处,但也有一些关键的区别和优势。本文将通过详细分析这两个框架的特性、用法和示例代码,为读者提供更全面的了解。一、iBatis特性:iBatis是目前较为老旧的持久化框架,它使用SQL映射文件

详解MyBatis注解与动态SQL的操作步骤详解MyBatis注解与动态SQL的操作步骤Feb 18, 2024 pm 03:29 PM

MyBatis注解动态SQL的使用方法详解IntroductiontotheusageofMyBatisannotationdynamicSQLMyBatis是一个持久层框架,为我们提供了便捷的持久化操作。在实际开发中,通常需要根据业务需求来动态生成SQL语句,以实现灵活的数据操作。MyBatis注解动态SQL正是为了满足这一需求而设计的,本

Linux性能调优~Linux性能调优~Feb 12, 2024 pm 03:30 PM

Linux操作系统是一个开源产品,它也是一个开源软件的实践和应用平台。在这个平台下,有无数的开源软件支撑,如apache、tomcat、mysql、php等。开源软件的最大理念是自由和开放。因此,作为一个开源平台,linux的目标是通过这些开源软件的支持,以最低廉的成本,达到应用最优的性能。谈到性能问题,主要实现的是linux操作系统和应用程序的最佳结合。一、性能问题综述系统的性能是指操作系统完成任务的有效性、稳定性和响应速度。Linux系统管理员可能经常会遇到系统不稳定、响应速度慢等问题,例如

MySQL如何声明变量MySQL如何声明变量Feb 18, 2024 pm 01:53 PM

MySQL是一种常用的关系型数据库管理系统,它支持变量的定义和使用。在MySQL中,我们可以使用SET语句来定义变量,并使用SELECT语句来使用已定义的变量。下面将通过具体的代码示例来介绍如何在MySQL中进行变量的定义和使用。首先,我们需要连接到MySQL数据库。可以使用以下命令连接到MySQL数据库:mysql-u用户名-p密码接下来,我们可以

如何解决 Golang 中的错误“ORA-00911:无效字符”?如何解决 Golang 中的错误“ORA-00911:无效字符”?Feb 08, 2024 pm 09:39 PM

我在调用以下函数时遇到错误“ORA-00911:无效字符”。如果我使用带有硬编码值的SQL查询(截至目前,它已在下面的代码片段中注释掉),那么我可以在邮递员中以JSON响应获取数据库记录,没有任何问题。所以,看起来我的论点做错了。仅供参考,我正在使用“github.com/sijms/go-ora/v2”包连接到oracledb。另外,“DashboardRecordsRequest”结构位于数据模型包中,但我已将其粘贴到下面的代码片段中以供参考。请注意,当我进行POC时,我们将使用存

比较JPA和MyBatis:如何确定最适合的持久化框架?比较JPA和MyBatis:如何确定最适合的持久化框架?Feb 18, 2024 pm 02:12 PM

JPAvsMyBatis:如何选择最佳的持久化框架?引言:在现代软件开发中,使用持久化框架来处理数据库操作是必不可少的。JPA(Java持久化API)和MyBatis是两个常用的持久化框架。然而,如何选择最适合你的项目的持久化框架是一个具有挑战性的任务。本文将分析JPA和MyBatis的特点,并提供具体的代码示例,帮助你做出更明智的选择。JPA的特点:J

深入了解MyBatis标签:掌握MyBatis常用标签的功能和用法深入了解MyBatis标签:掌握MyBatis常用标签的功能和用法Feb 18, 2024 pm 03:43 PM

MyBatis标签详解:掌握MyBatis中各种常用标签的功能与用法,需要具体代码示例引言:MyBatis是一个强大且灵活的Java持久化框架,广泛应用于Java开发中。了解MyBatis标签的功能和用法对于使用MyBatis进行数据库操作非常重要。本文将详细介绍MyBatis中几个常用的标签,并提供相应的代码示例。一、select标签select标签用于执

备份数据库的sql语句有哪些备份数据库的sql语句有哪些Sep 18, 2023 am 11:26 AM

备份数据库的sql语句有mysqldump命令、pg_dump命令、expdp命令、BACKUP DATABASE命令、mongodump命令和redis-cli命令。

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

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools