Laravel中简单使用Repository模式

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

这里写图片描述


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

这里写图片描述

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


TestRepository.php

<?php

namespace 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层总对数据库的操作,使代码更加规范简洁。
  • 6
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值