drhwb470572 2009-06-20 00:32
浏览 23
已采纳

这个PHP代码是根据OO原则正确编写的吗?

Iv been trying to get my head around object orientation and I think iv started to get some of the concepts, but im not sure. Making a google search that answers if my train of thought is correct proved to be quite hard so I decided to ask here really quick, please tell me if the question is against any rules.

Im I thinking correctly in regards to messagepassing? What are the obviously bad things? How should I think while going forward with my learning? Like getpagecontent($page, $connection); etc

Atm im reading [Oreilly - Learning php and mysql][1] and [Programming in an Object-Oriented Environment][2] And some books on UML

Here is the code.

dbfunctions.php

<?php
class dbconnect {

    function dbconnect() {
    $this->dbhost = 'xx';
    $this->dbuser = 'xx';
    $this->dbpass = 'xx';
    $this->dbdatabase = 'xx';
    }

    function createdbconnection() {
        require_once('DB.php'); // pear

        $this->connection = DB::connect("mysql://$this->dbuser:$this->dbpass@$this->dbhost/$this->dbdatabase");

        if (DB::isError($this->connection)) {
        die("Could not connect (connection)<br>" . DB::errorMessage($this->connection));
        }
    }

    function closedbconnection(){
        $this->connection->disconnect();
    }
}

class dbinteractions {

   function dbinteractions($connection) {
            $this->connection = $connection;
        }

   function searchdb($qstring) {
    if (get_magic_quotes_gpc()) {
        $qstring = stripslashes($qstring);
    }

    $qstring = mysql_real_escape_string($qstring);

    $query = "SELECT content FROM site_content WHERE content LIKE '%$qstring%'";
    $result = $this->connection->query($query);

    if(DB::isError($result)) {
        die("Could not connect (query)<br>" . DB::errorMessage($result));
    }

    while($result_row = $result->fetchRow()) {
        echo("<h2>Resultat:</h2>");
        foreach($result_row as $out)
            echo($out . "<p>");
    }
}

    function getpagecontent($page) {
        $query = "SELECT * FROM site_content WHERE (page_id = \"" . $page . "\")";
        $result = $this->connection->query($query);;

        while($result_row = $result->fetchRow()) {
            echo "<h1>" . $result_row[0] . "</h1>"; //Echo page_id
            echo $result_row[1]; //Echo content
            echo "<h2>" . $result_row[2] . "</h2>"; //Echo timestamp
        }
    }

}
?>

search.php

<?php
function displaysearchform()
{
    echo("<p></p>");
    if($_GET["search"] == '') { //Display search box if no search ?>

        <form method="GET" action="<?php echo(htmlentities($_SERVER['PHP_SELF'])); ?>">
            <label>
                Search: <input type="text" name="search" />
            </label>
            <input type="submit" value="Go!">
        </form>

    <?php
        return false;
    }
    else
    {
        return true;
    }
}

?>

index.php

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<link rel="stylesheet" href="style.css" type="text/css">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title></title>
</head>
<body>
    <div id="container">
        <div id="sidebar">
            <a href="?id=1">1</a><br>
            <a href="?id=2">2</a><br>
        </div>
        <div id="main">

            <?php
                include("dbfunctions.php");
                include("search.php");

                $dbconnect = new dbconnect();

                $dbconnect->createdbconnection();

                $dbinteractions = new dbinteractions($dbconnect->connection);

                if(!$_GET["id"] && $_GET["search"] == "") { //Check if direct site hit and no search query
                    $dbinteractions->getpagecontent("1");
                    }

                else  {
                    $page = $_GET["id"];
                    $dbinteractions->getpagecontent($page); //Get and display page content
                }

                if (displaysearchform() == true){ //If search was made don't display searchform
                    $dbinteractions->searchdb($_GET["search"]);
                }

                $dbconnect->closedbconnection(); //Close connection to db
            ?>
        </div>
    </div>
</body>
</html>
  • 写回答

7条回答 默认 最新

  • dongxifu5009 2009-06-20 01:26
    关注

    I can't say there's really much OOP here, but it sounds and looks more like you are trying to learn a good approach with parameters instead of using globals - which you seem to have accomplished.

    If you want to improve more from this code, here are some pointers

    • Try using a consistent coding style. For example, the PEAR coding standard is commonly used in PHP
    • Change your database code into a class, which encapsulates the connection object. For example, you could have a Database class with methods connect, search and close
    • Use some templating solution with your HTML code. You can use PHP itself as a templating language, as demonstrated here. The main idea is that you separate "application logic" from "view logic"
    • You may also want to modify your functions which use echo to simply return the result, and use another function (or just code in your template) to output them. Usually, you would want a function either provide/fetch data or output data, not both.

    Lastly, I'd suggest looking at some of the popular PHP frameworks, as they usually follow good OOP coding styles. CakePHP should be easy to start with, but because it uses PHP4, it doesn't always do OOP very well. You could get comfortable with the principles with Cake, and then move on to something like Symfony or Zend Framework. My own coding style got much better after I started using Zend Fw.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(6条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度