这篇文章主要介绍了laravelrepository模式使用,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
什么是Repository模式,laravel学院中用这样一张图来解释
编码过程当中 解耦一直是个较为热门的话题。 使用MVC设计模式开发的时候,如果需要查询数据库/操作数据库的时候就得直接引用模型,调用模型。按照常规的调用方法直接以下所示,不使用Eloquent ORM就没法操作数据库,那么就是ORM和这个控制器有着非常之大的耦合性。
$position = Position::createPosition($params);
$position->users()->attach($userParams);
$position->permissions()->attach($permissionParams);
控制器方面应该是只有返回相关的 不会包含任何逻辑的代码,所以为了解耦我们就该引用repository设计模式。
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模式使用的文章就介绍到这了,更多相关laravel repository模式内容请搜索编程学习网以前的文章希望大家以后多多支持编程学习网!
本文标题为:laravel 中repository模式使用详解


基础教程推荐
- PHP实现生成数据字典功能示例 2022-10-18
- PHP使用SMTP邮件服务器发送邮件示例 2022-11-16
- PHP数据加密方式梳理介绍 2023-07-03
- laravel model模型定义实现开启自动管理时间created_at,updated_at 2023-03-02
- thinkPHP3.2.2框架行为扩展及demo示例 2022-11-07
- php中使用array_filter()函数过滤数组实例讲解 2023-05-19
- TP5(thinkPHP5框架)基于bootstrap实现的单图上传插件用法示例 2023-01-19
- PHP实现创建一个RPC服务操作示例 2023-04-01
- PHP删除数组中指定值的元素常用方法实例分析【4种方法】 2022-11-12
- TP5 连接多个数据库及使用方法 2023-08-30