MVC 难题:如何解决这个问题并让逻辑远离视图?
我正在使用 CakePHP 构建一个网站,但这个问题更多的是关于解决 MVC 问题,而不是 CakePHP 问题。
我有一个用户模型和一个组模型。这是一种HABTM关系,因此不同的用户可能属于多个组。我网站上的一个控制器负责处理博客。它有很多方法,但所有视图都与相关帖子等共享一个侧边栏元素。我想向博客的侧边栏添加一些链接,只有属于管理员组的用户才能看到。
起初,我决定仅在用户所属的每个组中循环查看元素,如果找到管理组,则回显链接并中断循环。
但这似乎打破了MVC模式。有更好的办法吗?
I'm building a site with CakePHP, but this question is more about solving an MVC problem than it is a CakePHP problem.
I have a User Model and a Group Model. This is a HABTM relationship, so different users may belong to multiple groups. One controller on my website handles the blog. It has many methods, but all of the views share a sidebar element with things like related posts, etc. I want to add some links to the sidebar of the blog that only a user who belongs to the Admin group can see.
At first I decided to just loop in the view element through each group that the user belongs-to, and if the Admin group is found, echo the links and break the loop.
But this seems to break the MVC pattern. Is there a better way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只需在 User 模型中实现一个 isAdmin() 布尔方法,该方法将封装权限检查逻辑,然后从视图中调用它来检查给定用户是否是管理员。
根据经验,将所有业务逻辑保留在模型中。
Just implement an
isAdmin()
boolean method in the User model which will encapsulate the permission checking logic, then invoke it from a view to check whether a given user is an admin or not.As a rule of thumb, keep all the business logic in the models.