laravel下如何引入repository模式并使用
Admin 2022-08-03 群英技术资讯 509 次浏览
什么是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注入到其中 就可以书写逻辑以及相关编码了。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
猜你喜欢
PHP与MySQL的连接有三种API接口,分别是:PHP的MySQL扩展 、PHP的mysqli扩展 、PHP数据对象(PDO)。本文将详解这三种方式的示例代码,需要的可以参考一下
__construct(),__destruct(),__call(),__callStatic(),__get(),__set(),__isset(),__unset(),__sleep(),__wakeup(),__toString(),__invoke(),__set_state()...
本文实例总结了PHP常用字符串函数用法。分享给大家供大家参考,具体如下
本文的中心内容如题所述,就是教大家如何实现在单击按钮时调用PHP函数,其实关于调用PHP函数有很多方法,除了通过单击按钮执行此操作之外,还可以使用 Ajax、JavaScript 和 JQuery 调用 PHP 函数。
这篇文章主要介绍了php适配器模式简单应用,结合实例形式分析php适配器模式原理及使用适配器模式创建的天气预报查询接口功能相关操作技巧,需要的朋友可以参考下
成为群英会员,开启智能安全云计算之旅
立即注册Copyright © QY Network Company Ltd. All Rights Reserved. 2003-2020 群英 版权所有
增值电信经营许可证 : B1.B2-20140078 粤ICP备09006778号 域名注册商资质 粤 D3.1-20240008