laravel设计模式及实际应用之Repository模式
为什么要用Repository设计模式:
传统的MVC模式虽然十分成熟:但是无论是 controller直接调用model 或者直接使用构造器方法完成
数据交互,都会使得整个项目高耦合,而这部分臃肿的逻辑代码,既不能写在model中,
也要避免放在controller中,所以只能构造一个中间部门去储存编写它,这就是Repository
核心:Controller 就负责请求的逻辑调用,Model 只负责数据库的交互,而Repository就需要将两者连接起来,负责实现coroller需要的逻辑代码,负责从数据库去存储数据。
原理:一:接口绑定:
1. 在新建的Repository下 创建一个接口(供controller调用)
2. 在该目录下创建一个实现类,去实现这个接口的方法(核心代码逻辑)
3.在服务提供者下(可以自定义服务提供者,这样就省了第4步) 将实体类和 interface 类绑定
`public function register()
{
$this->app->bind('App\Repository\TestInterface', 'App\Repository\TestRepository');
}`
4.将自定义的服务提供者注册到config/app.php中的providers数组下
二:依赖注入:
protected $test;
public function __construct(TestInterface $testinterface){
$this->test =$testinterface;
}
特别注意:无论是自己定义provider还是使用原来存在的provider,在执行依赖注入的时候,使用的都是服务接口,例如TestInterface,而不是服务提供者TestProvider.