Dan*_*Dan 3 php oop model-view-controller class
如果您正在使用mvc来构建用户配置文件,那么最好是使用条件语句来计算模型或控制器中函数的注释的显示类型,如下所示:
例如, 我有3个班级
一些示例使用伪代码,其中缺少函数
选项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 }
}
Run Code Online (Sandbox Code Playgroud)
然后使用控制器中的代码来确定依赖于登录的用户类型显示哪个?
$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';
Run Code Online (Sandbox Code Playgroud)
选项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;
}
}
Run Code Online (Sandbox Code Playgroud)
使用如下控制器:
$profile = new profile($profileId);
$comments = $profile->showComments();
require 'templates/profile.php';
Run Code Online (Sandbox Code Playgroud)
技术上要么是正确的.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() {}
}
Run Code Online (Sandbox Code Playgroud)
在控制器中,$ user应该被实例化为管理员,成员或用户(这可以通过静态工厂或直接在控制器中完成).之后你的控制器很简单
if ($user->isLoggedIn()) {
$comments = $user->showComments($profileId);
}
Run Code Online (Sandbox Code Playgroud)
(为了使这更聪明,可以将profileId设置为类属性(除非用户有多个配置文件?)
选项2,otoh,是模型到模型设计的智能使用.
我看到的唯一真正的区别是你如何概念化评论.您是否认为它们是用户的一部分(与配置文件的联系较弱)?或者是个人资料的一部分(与用户关系薄弱)?这两种方法都没有任何特殊的痛点,我看到了它,所以最好的选择是运行最适合你的那个.