Laravel中简单使用Repository模式

来源:互联网 发布:团购用什么软件 编辑:程序博客网 时间:2024/05/21 18:30

什么是Repository模式,laravel学院中用这样一张图来解释

这里写图片描述


其实将这个模式用在项目中就是为了将业务逻辑和具体的调用分开,创建一个仓库来存放这些业务逻辑。那么我们怎么使用呢?

这里写图片描述

建立Repository目录来存放不同的业务逻辑
在Contracts中存放接口文件,Eloquent中存放具体的实现方法


TestRepository.php

<?phpnamespace App\Repository\Test\Eloquent;use App\Repository\Test\Contracts\TestRepositoryInterface;class TestRepository implements TestRepositoryInterface{    public function test()    {        return 'this is test repository';    }}

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:provider RepositoryServiceProvider
编写你自己的服务提供者
app\Providers\RepositoryServiceProvider.php注册Test仓库

    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,]

总结

通过这种方式我们可以将不同的业务逻辑分别创建一个仓库用来存放具体的方法,而在controller层只管调用不用去管具体的实现,也减少了controller层总对数据库的操作,使代码更加规范简洁。
1 0
原创粉丝点击