Laravel Repository 仓库模式实践

8 篇文章 0 订阅
7 篇文章 2 订阅

1 新建仓库目录

app/Repository                       # 仓库目录
  |--app/Repository/Interfaces       # 仓库接口定义
  |--app/Repository/Repositories     # 仓库接口实现

2 定义接口

# app/Repository/Interfaces/TestInterface.php

namespace App\Repository\Interfaces;

Interface TestInterface
{
    public function all();
}

3 接口实现

# app/Repository/Repositories/TestRepository.php

namespace App\Repository\Repositories;


use App\Repository\Interfaces\TestInterface;

class TestRepository Implements TestInterface
{
    public function all()
    {
        // TODO: Implement findPosts() method.
        return ['all'];
    }
}

4 接口绑定实现

4.1 创建一个服务

php artisan make:provider RepositoryServiceProvider

命令执行后会在 app/Providers 下创建 RepositoryServiceProvider.php 服务

4.2 将服务配置到应用中

app/config/app.php 中配置

'providers' => [
    ...
    App\Providers\RepositoryServiceProvider::class,
]

4.3 绑定接口

# app/Providers/RepositoryServiceProvider.php

/**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind('App\Repository\Interfaces\TestInterface', 'App\Repository\Repositories\TestRepository');
    }

5 仓库调用

5.1 创建控制器

 php artisan make:controller TestController

命令执行后会在 app/Http/Controllers 下生成 TestController.php

5.2 调用实现

# app/Http/Controllers/TestController.php

<?php

namespace App\Http\Controllers;


use App\Repository\Interfaces\TestInterface;

class TestController extends Controller
{
    public $testRepo;

    public function __construct(TestInterface $test)
    {
        $this->testRepo = $test;
    }

    public function index()
    {
        $res = $this->testRepo->all();
        return $res;
    }
}

6 配置路由在浏览器中访问

# app/routes/web.php

Route::get('test', 'TestController@index');
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值