Laravel Repository 模式

Repository 模式

为了保持代码的整洁性和可读性,使用 ​​Repository Pattern​​ 是非常有用的。事实上,我们也不必仅仅为了使用这个特别的设计模式去使用 ​​Laravel​​ ,然而在下面的场景下,我们将使用 ​​OOP​​ 的框架 ​​Laravel​​ 去展示如何使用 ​​repositories​​ 使我们的 ​​Controller​​ 层不再那么啰嗦、更加解耦和易读。下面让我们更深入的研究一下。

repositories


​Repositories​​ 并不是必要的,在你的应用中你完全可以不使用这个设计模式的前提下完成绝大多数的事情,然而随着时间的推移你可能把自己陷入一个死角,比如不选择使用 ​​Repositories​​​​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'));
}
}

​Eloquent​​ 和数据库交互,这段代码工作的很正常,但是 ​​controller​​ 层对于 ​​Eloquent​​ 而言将是紧耦合的。在此我们可以注入一个 ​​repository​

repositories

​repository​

Repository

​app​​ 文件夹创建自己 ​​Repository ​​ 文件夹 ​​repositories​

Interface


​repository​​​​HouseRepositoryInterface.php​


<?php namespace App\Repositories;

interface HouseRepositoryInterface {
public function selectAll();

public function find($id);
}

Repository


​repository​​​​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);
}
}

4:创建后端服务提供



首先你需要理解所谓服务提供,请参考手册 ​​服务提供者​

​BackendServiceProvider.php​


<?php namespace App\Repositories;

use IlluminateSupportSeriveProvider;

class BackSerivePrivider extends ServiceProvider {

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


​provider​​​​controller​​ 层使用类型提示​​HouseRepositoryInterface​​ ,我们知道你将会使用 ​​DbHouseRepository​

​Providers Array​​​​providers ​​ 到app/config/app.php 中的  ​​providers​​ 数组里面,只需要在最后加上​​App\Repositories\BackendServiceProvider::class,​

controller


​Controller​​​​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'));
}
}

这样 整个模式的转换就完成了