条件语句属于php mvc中的模型或控制器吗?
如果您正在使用mvc来构建用户配置文件,那么最好是使用条件语句来计算模型或控制器中函数的注释的显示类型,如下所示:
例如 >评论 一些示例使用伪代码,其中缺少函数 选项1 依赖于登录showComments函数的用户类型,返回注释将返回不同的信息. class user { function isLoggedIn() { //Check if a user is logged in } function getUserType() { // return user type } function showComments($id) { //comments code } } class admin extends user { function showComments($id) { //comments code } } 然后使用控制器中的代码来确定依赖于登录的用户类型显示哪个? $profileContent = $user->getOtherContent(); if ($user->isLoggedIn() && $user->getUserType() == "member") { $member = new member(); $comments = $member->showComments($profileId); } elseif ($user->isLoggedIn() && $user->getUserType() == "admin") { $admin = new admin(); $comments = $admin->showComments($profileId); } else $comments = $user->showComments($profileId); require 'templates/profile.php'; 选项2 由于这是一个自定义框架,我可以将所有内容移动到模型中的函数中,并在用户中使用一个函数来检查要显示的注释类型: abstract class user { function isLoggedIn() { //Check if a user is logged in } function getUserType() { // return user type } } class profile { function showComments($profileId,$user) { if (User::isLoggedIn() && User::getUserType() == "member") { $comments = //database query and formatting for member } elseif (User::isLoggedIn() && User::getUserType() == "admin") { $comments = //database query and formatting for admin } else $comments = //database query and formatting for guest return $comments; } } 使用如下控制器: $profile = new profile($profileId); $comments = $profile->showComments(); require 'templates/profile.php'; 解决方法
技术上要么是正确的. MVC模式是故意抽象的,关于模型与控制器的适当领域是什么有一些争论.
根据您使用的确切框架,可能有一个“更好”的答案.否则,做你认为最有意义的事情. 更新 – 根据您的问题的变化,我想稍微调整一下我的答案: 对于选项1,设计模型更有意义: class user { function isLoggedIn() {} function getUserType() {} function showComments() {} } class admin extends user { function getUserType() {} function showComments() {} } class member extends user { function getUserType() {} function showComments() {} } 在控制器中,$user应该被实例化为管理员,成员或用户(这可以通过静态工厂或直接在控制器中完成).之后你的控制器很简单 if ($user->isLoggedIn()) { $comments = $user->showComments($profileId); } (为了使这更聪明,可以将profileId设置为类属性(除非用户有多个配置文件?) 选项2,otoh,是模型到模型设计的智能使用. 我看到的唯一真正的区别是你如何概念化评论.您是否认为它们是用户的一部分(与配置文件的联系较弱)?或者是个人资料的一部分(与用户关系薄弱)?这两种方法都没有任何特殊的痛点,我从蝙蝠中看到,所以最好的选择是运行对你最有意义的那个. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |