条件语句属于php mvc中的模型或控制器吗?

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了条件语句属于php mvc中的模型或控制器吗?脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
如果您正在使用Mvc来构建用户配置文件,那么最好是使用条件语句来计算模型或控制器中函数的注释的显示类型,如下所示:

例如
我有3节课

>评论
>会员
> Admin(扩展成员)

一些示例使用伪代码,其中缺少函数

选项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,是模型到模型设计的智能使用.

我看到的唯一真正的区别是你如何概念化评论.您是否认为它们是用户的一部分(与配置文件的联系较弱)?或者是个人资料的一部分(与用户关系薄弱)?这两种方法都没有任何特殊的痛点,我从蝙蝠中看到,所以最好的选择是运行对你最有意义的那个.

@H_777_69@

脚本宝典总结

以上是脚本宝典为你收集整理的条件语句属于php mvc中的模型或控制器吗?全部内容,希望文章能够帮你解决条件语句属于php mvc中的模型或控制器吗?所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。