Laravel Repository Pattern

 

The Repository Pattern can be very helpful to you in order to keep your code a little cleaner and more readable. In fact, you don’t have to be using Laravel in order to use this particular design pattern. For this episode however, we will use the object oriented php framework Laravel to show how using repositories will make our controllers a bit less verbose, more loosely coupled, and easier to read. Let’s jump in!


Working Without Repositories

Using repositories is not mandatory! You can accomplish many great things in your applications without using this pattern, however, over time you may be painting yourself into a corner. For example by choosing not to use repositories, your application is not easily tested and swapping out implementations would be cumbersome. Let’s look at an example.

Getting House Listings From a Real Estate Database

HousesController.php

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?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 would be pretty typical code for using Eloquent to interact with the database which holds listings of houses for sale. It will work just fine, but the controller is now tightly coupled to Eloquent. We can inject a repository instead to create a loosely coupled version of the same code. This loose coupling makes it easy to swap implementations at a later time.


Working With Repositories

There are a fair number of steps to complete the entire repository pattern, but once you go through it a few times it becomes second nature. We’re going to cover every step here.

    • 1: Create the Repository Folder

We recently looked at a common Laravel File Structure you might be using. This creates a folder in the app directory to hold all of your domain specific files. For this example we’ll create the repotutrepositories within our app folder to contain our files. This also sets up our namespace structure which we will need to keep in mind for the files we create.

    • 2: Create Your Interface

The next step is to create the interface which will determine the contract our repository must implement. This just lays out the methods that must be present in our repository. Our Interface will look like the following. Note the namespace and methods we will use.

HouseRepositoryInterface.php

 
1
2
3
4
5
6
7
8
9
10
<?php
namespace repotutrepositories;
 
interface HouseRepositoryInterface {
 
public function selectAll();
 
public function find($id);
 
}
    • 3: Create Your Repository

We can now create the repository which will do all of the heavy lifting for us. It is in this file that we can put all of our detailed Eloquent queries, no matter how complex they may become. Each method simply has a custom name so that in our controller, we can just write some very short code to get the desired result. Again note the namespace and the use House; statement.

DbHouseRepository.php

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?php
namespace repotutrepositories;
 
use House;
 
class DbHouseRepository implements HouseRepositoryInterface {
 
public function selectAll()
{
return House::all();
}
 
public function find($id)
{
return House::find($id);
}
}
    • 4: Create Backend Service Provider

For our controller, we are going to type hint an interface. We are going to be doing dependency injection, but by way of an interface essentially. What this means is that we need to register the interface with Laravel so that it knows which implementation of our interface we want to use. We’ll first use an Eloquent implementation, but later we’ll move to a File based implementation to show how we can swap implementations easily using an interface. We place this Service Provider in the same namespace as our other files so far.

BackendServiceProvider.php

 
1
2
3
4
5
6
7
8
9
10
11
12
<?php
namespace repotutrepositories;
 
use IlluminateSupportServiceProvider;
 
class BackendServiceProvider extends ServiceProvider {
 
public function register()
{
$this->app->bind('repotutrepositoriesHouseRepositoryInterface', 'repotutrepositoriesDbHouseRepository');
}
}

This code basically says, when you see the controller type hinting HouseRepositoryInterface, we know you want to make use of the DbHouseRepository.

    • 5: Update Your Providers Array

Now that we have created a new Service Provider, we need to add this to the providers array within app/config/app.php. It may look something like this once complete:

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
'providers' => array(
 
'IlluminateFoundationProvidersArtisanServiceProvider',
'IlluminateAuthAuthServiceProvider',
'IlluminateCacheCacheServiceProvider',
'IlluminateSessionCommandsServiceProvider',
'IlluminateFoundationProvidersConsoleSupportServiceProvider',
'IlluminateRoutingControllerServiceProvider',
'IlluminateCookieCookieServiceProvider',
'IlluminateDatabaseDatabaseServiceProvider',
'IlluminateEncryptionEncryptionServiceProvider',
'IlluminateFilesystemFilesystemServiceProvider',
'IlluminateHashingHashServiceProvider',
'IlluminateHtmlHtmlServiceProvider',
'IlluminateLogLogServiceProvider',
'IlluminateMailMailServiceProvider',
'IlluminateDatabaseMigrationServiceProvider',
'IlluminatePaginationPaginationServiceProvider',
'IlluminateQueueQueueServiceProvider',
'IlluminateRedisRedisServiceProvider',
'IlluminateRemoteRemoteServiceProvider',
'IlluminateAuthRemindersReminderServiceProvider',
'IlluminateDatabaseSeedServiceProvider',
'IlluminateSessionSessionServiceProvider',
'IlluminateTranslationTranslationServiceProvider',
'IlluminateValidationValidationServiceProvider',
'IlluminateViewViewServiceProvider',
'IlluminateWorkbenchWorkbenchServiceProvider',
'repotutrepositoriesBackendServiceProvider'
 
),
    • 6: Update Your Controller for Dependency Injection

We have most of the groundwork in place. We can now update the Controller to facilitate injecting an implementation of the HouseRepositoryInterface. This will all us to remove any calls to Eloquent directly in the Controller, and replace those with simple custom method calls. Our updated controller might look something like this:

HousesController.php

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<?php
 
use repotutrepositoriesHouseRepositoryInterface;
 
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'));
 
}
}
    • 7: Confirm Routes are Correct

For this example we simply set up a route resource like so:

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php
 
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the Closure to execute when that URI is requested.
|
*/
 
Route::resource('houses', 'HousesController');
    • 8: Update composer.json

If you have not done so already, make sure that the namespace we are referencing is in your composer.json. Note the addition of "psr-4":{"repotut\": "app/repotut" } which tells composer to autoload the classes within the repotut namespace.

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
{
"name": "laravel/laravel",
"description": "The Laravel Framework.",
"keywords": ["framework", "laravel"],
"license": "MIT",
"require": {
"laravel/framework": "4.2.*"
},
"autoload": {
"classmap": [
"app/commands",
"app/controllers",
"app/models",
"app/database/migrations",
"app/database/seeds",
"app/tests/TestCase.php"
],
            
                "psr-4":{
                     "repotut\": "app/repotut"
                }
},
"scripts": {
"post-install-cmd": [
"php artisan clear-compiled",
"php artisan optimize"
],
"post-update-cmd": [
"php artisan clear-compiled",
"php artisan optimize"
],
"post-create-project-cmd": [
"php artisan key:generate"
]
},
"config": {
"preferred-install": "dist"
},
"minimum-stability": "stable"
}

Don’t forget to run composer dump after updating composer.json!


Whoa! Nice work partner, let’s test it in the browser. We can visit http://localhost/repotut/public/houses and we can see that we have 3 houses for sale, each a different color.


Easy To Change Implementations

Let’s say in the future you decide that Eloquent is not the way you want to handle storing data with your app. No problem! Since you already laid out the ground work for using an interface, you can simple create a new repository and change the Service Provider. Let’s see how we can swap implementations.

    • 1: Create a New Repository

We’ll just use a quick example here. Let’s pretend this is a whole file system class which provides data storage via flat files. In our case, we’ll just put some simple logic in to test swapping implementations. Note that this class implements the same exact methods as the Eloquent version we tested prior.

FileHouseRepository.php

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<?php
namespace repotutrepositories;
 
class FileHouseRepository implements HouseRepositoryInterface {
 
public function selectAll()
{
$houses = new stdClass;
 
$house1 = new stdClass;
$house1->color = 'Olive';
 
$house2 = new stdClass;
$house2->color = 'Yellow';
 
$house3 = new stdClass;
$house3->color = 'Brown';
 
$houses = array($house1,$house2,$house3);
 
return $houses;
}
 
public function find($id)
{
return 'Here is a single house listing, again using the file system';
}
}
    • 2: Update Service Provider

Now in the Service Provider, all we have to do is change one single line of code! We simply tell Laravel that now when you see the HouseRepositoryInterface, you will use the FileHouseRepository instead of the DbHouseRepository.

 
1
2
3
4
5
6
7
8
9
10
11
12
<?php
namespace repotutrepositories;
 
use IlluminateSupportServiceProvider;
 
class BackendServiceProvider extends ServiceProvider {
 
public function register()
{
$this->app->bind('repotutrepositoriesHouseRepositoryInterface', 'repotutrepositoriesFileHouseRepository');
}
}

When we test it in the browser at http://localhost/repotut/public/houses we can see that the new implementation has indeed taken effect, very cool!

Repositories Conclusion

As you can see, it seems like a lot of steps to get Repositories working in your application. There are a few steps involved, no doubt about it. If you are going to be responsible for maintaining a piece of code for the long term however, you are going to reap the benefits of taking the time to correctly architect your app in the beginning. Consider it a form of delayed gratification, which in this day and age seems like a forgotten art.

Laravel Repository Pattern的更多相关文章

  1. Laravel与Repository Pattern(仓库模式)

    为什么要学习Repository Pattern(仓库模式) Repository 模式主要思想是建立一个数据操作代理层,把controller里的数据操作剥离出来,这样做有几个好处: 把数据处理逻辑 ...

  2. How To Use The Repository Pattern In Laravel

    The Repository Pattern in Laravel is a very useful pattern with a couple of great uses. The first us ...

  3. Laravel Repository 模式

    Repository 模式 为了保持代码的整洁性和可读性,使用Repository Pattern 是非常有用的.事实上,我们也不必仅仅为了使用这个特别的设计模式去使用Laravel,然而在下面的场景 ...

  4. Follow me to learn what is repository pattern

    Introduction Creating a generic repository pattern in an mvc application with entity framework is th ...

  5. Generic repository pattern and Unit of work with Entity framework

    原文 Generic repository pattern and Unit of work with Entity framework Repository pattern is an abstra ...

  6. Using the Repository Pattern with ASP.NET MVC and Entity Framework

    原文:http://www.codeguru.com/csharp/.net/net_asp/mvc/using-the-repository-pattern-with-asp.net-mvc-and ...

  7. Using Repository Pattern in Entity Framework

    One of the most common pattern is followed in the world of Entity Framework is “Repository Pattern”. ...

  8. 学习笔记之ASP.NET MVC & MVVM & The Repository Pattern

    ASP.NET MVC | The ASP.NET Site https://www.asp.net/mvc ASP.NET MVC gives you a powerful, patterns-ba ...

  9. [转]Using the Repository Pattern with ASP.NET MVC and Entity Framework

    本文转自:http://www.codeguru.com/csharp/.net/net_asp/mvc/using-the-repository-pattern-with-asp.net-mvc-a ...

随机推荐

  1. 剑指offer48:不用加减乘除做加法

    1 题目描述 写一个函数,求两个整数之和,要求在函数体内不得使用+.-.*./四则运算符号. 2 思路和方法 位运算符:两个数异或(^)[1^0=1, 1^1=0, 0^0=0, 0^1=1, 5^5 ...

  2. Redis 的基本操作、Key的操作及命名规范

    Redis基本操作 查看数据的状态 pong redis 给我们返回 PONG,表示 redis 服务 运行正常 redis 默认用 使用 16 个 库 • Redis 默认使用 16 个库,从 0 ...

  3. 08 IO流(五)——文件字符流FileWriter/FileReader

    对比文件字节流的优势 对于文本文件的数据传输,使用文件字符流,就不用考虑编码转码的问题. 对比文件字节流,在方法上的不同有哪些 文件字符流有append方法: Writer append(char c ...

  4. WUSTOJ 1336: Lucky Boy(Java)博弈

    题目链接:1336: Lucky Boy 参考博客:LUCKY BOY 博弈--HandsomeHow Description Recently, Lur have a good luck. He i ...

  5. Vector、ArrayList异同和HTTP请求异同的概括和区别

    今天我所记录的是两个异同的概括: HTTP: 同步请求:提交请求->等待服务器处理->处理完毕返回给客户端  这个期间客户端浏览器只能处于等待状态,得到回应才可以执行下一步操作. 异步请求 ...

  6. Hibernate常用api以及增删改查

    一   .API的定义 所谓的API全称就是(Application Programming Interface,应用程序编程接口).就是类库对外提供的接口.类.枚举.注解等元素. 如:JDK API ...

  7. pyrhon 第一个小购物车例子

    product_list=[[],[],[],[]] shopping_list=[] salary = input("请输入你的工资:") if salary.isdigit() ...

  8. 效率提升工具Listary

    效率提升工具Listary https://baijiahao.baidu.com/s?id=1590032175308204846&wfr=spider&for=pc

  9. 【转载】C#通过IndexOf方法判断某个字符串是否包含在另一个字符串中

    C#开发过程中针对字符串String类型的操作是常见操作,有时候需要判断某个字符串是否包含在另一个字符串,此时可以使用IndexOf方法以及Contain方法来实现此功能,Contain方法返回Tru ...

  10. 前端知识总结--ES6新特性

    ECMAScript 6.0(以下简称 ES6)是 JavaScript 语言的下一代标准,已经在 2015 年 6 月正式发布了.它的目标,是使得 JavaScript 语言可以用来编写复杂的大型应 ...