php – 尝试抽象数据库类并停止它的公共用法:Laravel 5.2.31
|
我有以下课程
接口 interface IRole {
public function All();
}
在下面的类中,我还会在将数据发送到数据库层之前编写一些逻辑,并在从Database类检索数据之后编写一些代码 class RoleBL implements IRole {
public function All() {
return (new RoleDb())->All();
}
}
数据库类 class RoleDb {
public function All() {
$Roles = AppModelsRoleRoleModel
::all();
return $Roles;
}
}
以下是我的控制器操作方法 class MembershipController extends AppHttpControllersBaseController
{
private $role;
public function __construct(IRole $_role) {
$this->role = $_role;
parent::__construct();
}
public function create() {
$RoleTypes = $this->role->All();
return view('Membership.Create',array('Roles' => $RoleTypes));
}
}
有人可以帮助我如何停止直接访问RoleDb类?它的访问修饰符现在是公共的. 解决方法
你甚至不应该尝试这样做.在PHP,它看起来更像黑客.只需保留一种代码风格,如果您在团队中工作,那么请编写一些指南.
根据目的将所有对象保存在不同的图层中.数据访问层中的数据库相关对象.域层中的域对象. 域层的模型代表业务谈论的所有业务对象(角色,客户,评论,支付等)及其上的所有相关操作(用户 – >注册,用户 – > assignRole,blog-> postArticle等).这些模型包含业务需求和规则. 数据访问层的模型表示持久保存这些业务对象状态并以特定方式查找它们的所有对象(blog-> getUnreadPosts,user-> findAdministrators等). 如果通过RoleBL,您的意思是角色业务逻辑,那么它应该是域的一部分(您的业务需求).这些对象由DAL持久保存/检索. 您的业??务对象不应该对数据访问层有任何了解. (new RoleDb()) – > All();意味着从数据库中读取要解决此问题,您可以在DAL创建单独的读取模型,以查询业务对象.这意味着在DAL上将有单独的模型(例如RoleDataModel),用于根据业务/应用程序需求设计查询端. namespace Domain
{
class Role
{
private $id;
private $title;
/* etc. */
public function getId()
{
return $this->id;
}
}
class Person
{
private $roles = [];
/* etc. */
public function assignRole(Role $role)
{
// person already promoted?
// can person be promoted ?
// if you promote person then it might not be required to add instance af this $role
// to $this->roles array,just add identifier from this role
// If you would like to respond on what did just happen
// at this point you can return events that describe just that
}
public function getRoles()
{
return $this->roles;
}
}
}
namespace DAL
{
class Person
{
function storePerson(Person $person)
{
// here you can use eloqueent for database actions
}
function getAllAdministrators()
{
}
}
}
雄辩的将有单独的Person类.仅用于数据操作.将数据从雄辩的objets映射到Data Transfet Objects或您的业务层对象. DTO可以更加特定于您的其他图层,例如UI,您可能不需要显示BLO包含的所有内容. UI的DTO将为UI所需的一切建模. 熟悉一些DDD和整体编程概念.我应该能够找到适合您需求的东西. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
