Laravel Repository 仓库模式实践

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/simplexingfupeng/article/details/82083395

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');

猜你喜欢

转载自blog.csdn.net/simplexingfupeng/article/details/82083395
今日推荐