Laravel Repository Pattern
Repository Pattern
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 special design pattern. However, in the following scenario, we will use the OOP
framework Laravel
to show how to use repositories
to make our Controller
Layers are less verbose, more decoupled and easier to read. 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 Putting yourself into a blind spot, for example, not choosing to use Repositories
will make your application testing very difficult, (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 very 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
of. 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.
Using repositories
It actually requires quite a few steps to complete the entire repository
pattern, but once you complete it a few times it will naturally become a habit. Below we will introduce each step in detail.
1. Create the Repository
folder
First we need to create our own Repository
folderrepositories
in the app
folder, and then each file in the folder must set the corresponding namespace.
2: Create the corresponding Interface
class
The second step is to create the corresponding interface, which determines the related methods that our repository
class must implement, as shown in the example below, where the namespace is emphasized again Be sure to remember to add it. 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 Most database queries are put in there, no matter how complex. As in the example belowDbHouseRepository.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><span> </span></span></code>
4: Create a backend service provider
First you need to understand the so-called service provider, please refer to the manual service providerBackendServiceProvider.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><span> </span></span></code>
Of course, you can also create a new folder to mainly store our provider
related files.
The above code mainly says that when you use type hints HouseRepositoryInterface
in the controller
layer, we know that you will use DbHouseRepository
.
5: Update your Providers Array
actually above In the code, we have implemented a dependency injection, but if we want to use it, we need to write it manually. In order to be more convenient, we need to add this providers
to providers in app/config/app.php
In the array, just add AppRepositoriesBackendServiceProvider::class,
6 at the end: Finally, use dependency injection to update your controller
After we complete the above content, we only need to simple in Controller
The calling method replaces the previous complex database call, as shown below: HousesController.php
<?php use App\repositories\HouseRepositoryInterface; class HousesController extends BaseController { 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 conversion of the entire model is completed
The above has introduced the Laravel Repository mode, including aspects of it. I hope it will be helpful to friends who are interested in PHP tutorials.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Function means function. It is a reusable code block with specific functions. It is one of the basic components of a program. It can accept input parameters, perform specific operations, and return results. Its purpose is to encapsulate a reusable block of code. code to improve code reusability and maintainability.

Every year before Apple releases a new major version of iOS and macOS, users can download the beta version several months in advance and experience it first. Since the software is used by both the public and developers, Apple has launched developer and public versions, which are public beta versions of the developer beta version, for both. What is the difference between the developer version and the public version of iOS? Literally speaking, the developer version is a developer test version, and the public version is a public test version. The developer version and the public version target different audiences. The developer version is used by Apple for testing by developers. You need an Apple developer account to download and upgrade it.

In this article, we will learn about enumerate() function and the purpose of “enumerate()” function in Python. What is the enumerate() function? Python's enumerate() function accepts a data collection as a parameter and returns an enumeration object. Enumeration objects are returned as key-value pairs. The key is the index corresponding to each item, and the value is the items. Syntax enumerate(iterable,start) Parameters iterable - The passed in data collection can be returned as an enumeration object, called iterablestart - As the name suggests, the starting index of the enumeration object is defined by start. if we ignore

Detailed explanation of the role and function of the MySQL.proc table. MySQL is a popular relational database management system. When developers use MySQL, they often involve the creation and management of stored procedures (StoredProcedure). The MySQL.proc table is a very important system table. It stores information related to all stored procedures in the database, including the name, definition, parameters, etc. of the stored procedures. In this article, we will explain in detail the role and functionality of the MySQL.proc table

Usage and Function of Vue.use Function Vue is a popular front-end framework that provides many useful features and functions. One of them is the Vue.use function, which allows us to use plugins in Vue applications. This article will introduce the usage and function of the Vue.use function and provide some code examples. The basic usage of the Vue.use function is very simple, just call it before Vue is instantiated, passing in the plugin you want to use as a parameter. Here is a simple example: //Introduce and use the plug-in

The clearstatcache() function is used to clear the file status cache. PHP caches the information returned by the following functions −stat()lstat()file_exists()is_writable()is_readable()is_executable()is_file()is_dir()filegroup()fileowner()filesize()filetype()fileperms() What to do To provide better performance. Syntax voidclearstatecache() Parameter NA Return value clearstatcache(

The file_exists method checks whether a file or directory exists. It accepts as argument the path of the file or directory to be checked. Here's what it's used for - it's useful when you need to know if a file exists before processing it. This way, when creating a new file, you can use this function to know if the file already exists. Syntax file_exists($file_path) Parameters file_path - Set the path of the file or directory to be checked for existence. Required. Return file_exists() method returns. Returns TrueFalse if the file or directory exists, if the file or directory does not exist Example let us see a check for "candidate.txt" file and even if the file

With the development of the Internet, SOA (service-oriented architecture) has become an important technical architecture in today's enterprise-level systems. Services in the SOA architecture can be reused, reorganized and extended, while also simplifying the system development and maintenance process. As a widely used Web programming language, PHP also provides some function libraries for implementing SOA. Next, we will detail how to use SOA functions in PHP. 1. The basic concept of SOA. SOA is a distributed system development idea and architecture.
