陷入困境,需要帮助突破到一个新的水平

Dre*_*rew 8 php code-organization

我正在一个简陋的网站上工作,我的平庸,自学成才的PHP技能,目前的界面结构是这样的:

<?php
  if (A) {
    $output = someFunc(A);
  } else if (B) {
    $output = anotherFunc(B);
  } else if (C) {
    $output = yetAnotherFunc(C);
  } else {
    $output = 'default stuff';
  }
?>
<html template top half>

<?php echo $output; ?>

</html template bottom half>
Run Code Online (Sandbox Code Playgroud)

这起初工作正常,看起来组织得很好,但是所需的功能已经增长了10倍,并且很快变成了一个难以维护,令人尴尬的混乱,我不知道如何摆脱它.

我觉得为每种情况调用的函数都写得很好并且集中精力,但是如何处理用户和创建布局并处理返回的函数之间的中间步骤是不知所措的.

我觉得MVC是一个解决方案?但我很难掌握如何从这里到那里......

对于上述代码可能引发的任何令人头疼或不愉快的回忆,我深表歉意.感谢您的时间.

Bre*_*ley 5

你似乎已经开始了许多人的方式,一个大的if和/或case case声明继续增长.所有那些"如果"检查都需要时间.MVC绝对是一个很好的方法,但有很多方法可以实现它.我建议还要寻找通常与MVC一起使用的Front Controller设计模式.

改变工作方式的一种方法是使用关联数组切换到定义的"动作"列表.并将您的功能更改为包含.然后你可以有多个函数,变量和其他处理代码.

$actions = array(
'A'=>'action1.php',
'B'=>'action2.php',
'C'=>'action3.php',
'default'=>'action_default.php'
);
if ( isset( $actions[ $_GET['action'] ] ) ) {
    include( $actions[ $_GET['action'] ] );
} else {
    include( $actions['default'] );
}
Run Code Online (Sandbox Code Playgroud)

那么你的"索引"文件只是一个路由工具,它几乎就是前端控制器的概念.