对laravel的repository的使用

来源:互联网 发布:淘宝网天猫围巾 编辑:程序博客网 时间:2024/05/22 23:42

repository按照最初提出者的介绍,Repository 是衔接数据映射层和领域层之间的一个纽带,作用相当于一个在内存中的域对象集合。客户端对象把查询的一些实体进行组合,并把它 们提交给 Repository。对象能够从 Repository 中移除或者添加,就好比这些对象在一个 Collection 对象上进行数据操作,同时映射层的代码会对应的从数据库中取出相应的数据。

从概念上讲,Repository 是把一个数据存储区的数据给封装成对象的集合并提供了对这些集合的操作—–学院君

可以称repository为仓库模式
使用方法:
1 建立文件:APP/Repository/Test/Contracts
APP/Repository/Test/Eloquent
在Contracts中存放接口文件,Eloquent中存放具体的实现方法
在Contracts下建立TestRepositoryInterface.php:

<?php namespace App\Repository\Test\Contracts;use App\House;interface TestRepositoryInterface {    public function test();}

在Eloquent下建立TestRepository:

<?phpnamespace App\Repository\Test\Eloquent;use App\House;use App\Repository\Test\Contracts\TestRepositoryInterface;class TestRepository implements TestRepositoryInterface{    public function test()    {        $name = House::find(1)->name;        return $name;    }}

创建控制器和路由:
控制器TestController.php

<?php namespace App\Http\Controllers;use App\Http\Requests;use Illuminate\Http\Request;class TestController extends Controller{    public function test()    {        $test = app('Test');        $testInfo = $test->test();        echo $testInfo;    }}

编写服务提供者 执行php artisan make:providerRepositoryServiceProvider
编写你自己的服务提供者
app\Providers\RepositoryServiceProvider.php注册Test仓库
RepositoryServiceProvider.php:

 public function register()    {        $this->registerTestRepository();    }    public function provides()    {        $test = ['Test'];        return array_merge($test);    }    private function registerTestRepository()    {        $this->app->singleton('Test', 'App\Repository\Test\Eloquent\TestRepository');    }

在app.php的providers数组中添加我们的服务提供者

'providers' => [    App\Providers\RepositoryServiceProvider::class,]
1 0
原创粉丝点击