多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
[TOC] # 简介 Repository设计模式相当于在控制器层和model层中加了一层,这层是仓库的意思,存放model层中的一些数据 ![](https://box.kancloud.cn/3bec61da15ecac77370dbeb84102a4b2_1476x478.jpg) # 使用 ![](https://box.kancloud.cn/0bda17b76532c7d366d2da462a7471d1_480x1030.jpg) 建立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层总对数据库的操作,使代码更加规范简洁。