2023-01-14 492
什么是Repository模式,laravel学院中用这样一张图来解释
编码过程当中 解耦一直是个较为热门的话题。 使用MVC设计模式开发的时候,如果需要查询数据库/操作数据库的时候就得直接引用模型,调用模型。按照常规的调用方法直接以下所示,不使用Eloquent ORM就没法操作数据库,那么就是ORM和这个控制器有着非常之大的耦合性。
$position = Position::createPosition($params);
$position->users()->attach($userParams);
$position->permissions()->attach($permissionParams);
控制器方面应该是只有返回相关的 不会包含任何逻辑的代码,所以为了解耦我们就该引用repository设计模式。
首先我们需要定义一个接口
<?php
namespace App\Http\Repositories\Interfaces;
use App\Http\Repositories\Interfaces\BaseRepositoryInterface;
interface UserRepositoryInterface extends BaseRepositoryInterface
{
}
可以自己先构造一个基层的BaseInterface来封装常用并且基本的操作模型的方法,创建好接口之后开始绑定repository来进行实现该接口
<?php
namespace App\Http\Permission\Repositories\Eloquent;
use App\Http\Repositories\Eloquent\EloquentBaseRepository;
use App\Http\Permission\Repositories\Interfaces\UserRepositoryInterface;
class UserRepository extends EloquentBaseRepository implements UserRepositoryInterface
{
}
创建好之后需要在ServiceProvider当中注册并绑定该接口,保证与模型层有相关联。
$this->app->bind(UserRepositoryInterface::class,function (){
return new UserRepository(new User);
});
绑定好之后就可以创建service之后使用构造函数来将该interface注入到其中 就可以书写逻辑以及相关编码了。
以上所述是小编给大家介绍的laravel 中repository模式使用详解,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对77isp云服务器技术网的支持!
原文链接:https://77isp.com/post/25671.html
=========================================
https://77isp.com/ 为 “云服务器技术网” 唯一官方服务平台,请勿相信其他任何渠道。
数据库技术 2022-03-28
网站技术 2022-11-26
网站技术 2023-01-07
网站技术 2022-11-17
Windows相关 2022-02-23
网站技术 2023-01-14
Windows相关 2022-02-16
Windows相关 2022-02-16
Linux相关 2022-02-27
数据库技术 2022-02-20
抠敌 2023年10月23日
嚼餐 2023年10月23日
男忌 2023年10月22日
瓮仆 2023年10月22日
簿偌 2023年10月22日
扫码二维码
获取最新动态