【转载】在Laravel中使用Repository模式

转自:https://blog.csdn.net/sinat_21125451/article/details/54290962

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

建立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层总对数据库的操作,使代码更加规范

点赞

发表回复

电子邮件地址不会被公开。必填项已用 * 标注