doutuo3575 2013-10-25 13:05
浏览 63

混合PHP和HTML时集成Clean代码[关闭]

I'm finding an organisation a major problem with mixing PHP and HTML, it just looks horrible, so i'm wondering if it's a viable option to create a set of object oriented methods such as this:

class MainOO {

    public $Database;

    public function __construct($Server,$User, $Password, $DB){
        if ($this->Database = new mysqli($Server,$User,$Password,$DB)){
            return true;
        }
        return false;
    }

    public function User_Login(){

        $Get_Usr_Info = $this->Database->prepare("SELECT ID, Password, Salt FROM Users WHERE Username=?");
        $Get_Usr_Info->bind_param('s',$_POST['username']);
        $Get_Usr_Info->execute();
        $Get_Usr_Info->store_result();
        $User_Number = $Get_Usr_Info->num_rows;
        $Get_Usr_Info->bind_result($UserID, $Stored_Password, $Stored_Salt);
        $Get_Usr_Info->fetch();
        $Get_Usr_Info->close();
        if ($User_Number !== 1){
            $Error = "Wrong Username Specified Or Password Is Incorrect";
            header ("Location: index.php?Errors=".urlencode($Error));
            exit;
        }
        // Continue with login script 

    }
    public function Logout(){
        if (session_status() !== PHP_SESSION_DISABLED){
            session_destroy();
            header ("Location: LoggedOut.php");
            exit;
        }
    }


}

Then HTML side:

<?php 
  include "MainOO.php"; 
  $MainOO = new MainOO("host","user","password","database");
?>
<div class="example">
  <div class="example left">
  <?php
   $MainOO->User_Login();
  ?>
  </div>
</div>

It's still mixing PHP & HTML, but it's making look a hell of a lot neater than having heaps of PHP in the middle of HTML.

I'm fully aware I could migrate over to a MVC Framework (which this topic is looking like) already setup, or even use a template engine such as smarty, but I want to avoid this as much as possible.. So is this a viable option to have neater PHP code within html?

  • 写回答

1条回答 默认 最新

  • dongxieyou3314 2013-10-25 13:09
    关注

    You will probably want to use an isset() in the code too e.g

    <?= (isset($variable)) ? $variable : ''; ?>

    e.g if variable isset then display it otherwise display nothing

    评论

报告相同问题?

悬赏问题

  • ¥15 基于52单片机的酒精浓度检测系统加继电器和sim800
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等