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');
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。