简体   繁体   English

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

[英]Is this php code written correctly according to OO principles?

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. iv一直试图绕开面向对象的方向,我认为iv开始了解一些概念,但是我不确定。 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); 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 Atm im阅读[Oreilly-学习php和mysql] [1]和[在面向对象的环境中编程] [2]以及有关UML的一些书籍

Here is the code. 这是代码。

dbfunctions.php 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 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 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>

I'm not sure what you mean by object-oriented, but your code looks nothing like OO code in the traditional sense of classes, objects, and methods. 我不确定您所说的面向对象是什么意思,但是从传统的类,对象和方法的意义上讲,您的代码看起来并不像OO代码。 When most people say "OO", they mean that their code is built off of different types of objects that you can call methods on. 当大多数人说“ OO”时,他们的意思是说他们的代码是建立在可以调用方法的不同类型的对象上的。

To me, your code looks like typical procedural code. 对我来说,您的代码看起来像典型的过程代码。

You're certainly using objects correctly, and you're accesing them correctly. 您当然可以正确使用对象,并且可以正确访问它们。 You're DB object is a singleton by the look of it, that's good. 从外观上看,您是DB对象,这很不错。 And you're using '->' to access other object methods and properties. 而且您正在使用'->'访问其他对象方法和属性。

But it looks like you're re implementing functionality that should be part of the DB object. 但是看起来您正在重新实现应作为数据库对象一部分的功能。 For example, with my own DB class that I have i'd do something like this 例如,使用我自己的数据库类,我会做这样的事情

$db = DBObject::getInstance(); // The DB object is a singleton

$sql = "Select * from.... etc etc";

$result = $db->query($sql);

Which I think should accomplish everything you've tried to do. 我认为应该可以完成您尝试做的所有事情。 The DB object should know how to connect to the database by itself, issue its own error messages and close the connection should it need to (which it probably doesn't). DB对象应该知道如何自行连接到数据库,发出自己的错误消息,并在需要时关闭连接(可能不需要)。 And stuff like handling quotes, slashes and making sure your Query is safe could all be handles inside the DB object as well. 处理引号,斜杠以及确保查询安全等之类的东西也都可以在DB对象内部处理。

But also, the procedure you're trying to perform could easily be a class all of its own (eg: PageRenderer). 而且,您尝试执行的过程可能很容易成为其自己的类(例如:PageRenderer)。 But here you've created a lot of functions which use other objects. 但是,这里您创建了很多使用其他对象的函数。

But it's hard to give you a straight answer. 但是很难给你一个直接的答案。 Yes, you're doing it right, but you seem to be doing too much. 是的,您做得对,但您似乎做得太多。

I think when you really like to write OO you should use objects which interact with each other to accomplish the task at hand. 我认为,当您真的很想写OO时,应该使用相互交互的对象来完成手头的任务。 I don't see any object instantiated from classes so I don't think this is proper Object oriented code. 我看不到任何从类实例化的对象,因此我认为这不是正确的面向对象的代码。 This is more procedural code if you ask me. 如果您问我,这是更多的程序代码。

You only have one thing right with OO. 您对OO只有一件事。 The $connection object. $ connection对象。

Everything else is procedural. 其他一切都是程序性的。 You should start by creating a class, instead of all those loose functions in "dbfunctions.php". 您应该首先创建一个类,而不是“ dbfunctions.php”中所有那些松散的函数。

Also note that you should avoid mixing logic code with HTML. 另请注意,您应避免将逻辑代码与HTML混合使用。 It gets hard to maintain. 很难维护。

Here's probably the best book you can read on the subject . 这可能是您可以阅读的最好的一本书

It's not easy to get into object oriented paradigm. 进入面向对象的范式并不容易。 But when you get it, it's like riding a bicycle. 但是,一旦您了解它,就像骑自行车一样。 You never forget. 你永远不会忘记。

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. 我不能说这里确实有很多OOP,但是听起来似乎更像是您在尝试学习一种使用参数的好方法,而不是使用全局变量-您似乎已经完成了。

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 例如,PHP中通常使用PEAR编码标准
  • 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 例如,您可能有一个数据库类,其类具有方法connectsearchclose
  • Use some templating solution with your HTML code. 在您的HTML代码中使用一些模板解决方案。 You can use PHP itself as a templating language, as demonstrated here . 您可以将PHP本身用作模板语言,如此处所示 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. 您可能还想修改使用echo的函数以简单地返回结果,并使用另一个函数(或只是模板中的代码)来输出它们。 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. 最后,我建议您看一些流行的PHP框架,因为它们通常遵循良好的OOP编码样式。 CakePHP should be easy to start with, but because it uses PHP4, it doesn't always do OOP very well. CakePHP应该很容易入手,但是因为它使用PHP4,所以OOP并不总是很好。 You could get comfortable with the principles with Cake, and then move on to something like Symfony or Zend Framework. 您可以对Cake的原理感到满意,然后继续使用Symfony或Zend Framework之类的东西。 My own coding style got much better after I started using Zend Fw. 在我开始使用Zend Fw之后,我自己的编码风格变得更好了。

I have a small advice about object oriented php programming; 我对面向对象的php编程有一些建议; firstly read the documentation in the php.net and finally you should read the book "Object-Oriented PHP" by No Starch Press -> http://nostarch.com/oophp.htm 首先阅读php.net中的文档,最后阅读No Starch Press-> http://nostarch.com/oophp.htm上的 “面向对象的PHP”一书。

Also , use this statement at the top of your class/function files with you will include(search and dbfunctions.php) 另外,在您的类/函数文件的顶部使用此语句,其中将包含(search和dbfunctions.php)

if (!defined('page')) exit('No direct script access allowed'); if(!defined('page'))exit('不允许直接脚本访问');

and define the page which uses this class - like as the sample in below: 并定义使用此类的页面-如以下示例所示:

define("page","search"); define(“ page”,“ search”); include("dbfunctions.php"); include(“ dbfunctions.php”); include("search.php"); include(“ search.php”);

i like to keep it simple and straight forward. 我喜欢保持简单明了。 Here's a class that I use, that was used in the book Beginning PHP and MySQL: From Novice to Professional by Jason Gilmore 这是我使用的一个类,该类在Jason Gilmore的《 Beginning PHP and MySQL:From Novice to Professional 》一书中使用。

<?php

class SQL {


    function __construct() {

        $this->host     = "xxx";

        $this->user     = "xxx";

        $this->password  = "xxx";

        $this->database  = "xxx";



        $this->result;

        $this->querycount;

        $this->connect();

        $this->select();        

    }



    function connect() {

        $this->linkid = @ mysql_connect($this->host, $this->user, $this->password);

        if(!$this->linkid) {

            echo "--[ could not connect to sql database ]--";   exit();

        }

    }



    function select() {

        if(!@ mysql_select_db($this->database, $this->linkid)) {

            echo "--[ could not select database ]--";   exit();

        }

    }




    function escape($data) {

        return mysql_real_escape_string(trim(htmlspecialchars($data)), $this->linkid);

    }



    function query($query) {

        if( $this->result = @ mysql_query($query, $this->linkid) ) {

            $this->querycount++;

            return true;

        } else {

            echo "<b>Error:</b>" . mysql_error($this->linkid);              

            return false;

        }   

    }



    function affectedRows() {

        $count =  @ mysql_affected_rows($this->linkid);

        return $count;

    }



    function numRows() {

        $count = @ mysql_num_rows($this->result);

        return $count;

    }



    function fetchObject() {

        $row = @ mysql_fetch_object($this->result);

        return $row;

    }



    function fetchRow() {

        $row = @ mysql_fetch_row($this->result);

        return $row;

    }



    function fetchArray() {

        $row = @ mysql_fetch_array($this->result);

        return $row;

    }



    function fetchAssoc() {

        $row = @ mysql_fetch_assoc($this->result);

        return $row;

    }



    function numQueries() {

        return $this->querycount;

    }

}



?>

I'm not saying it's the best way. 我并不是说这是最好的方法。 But it's very simple and straight forward; 但这很简单直接。 and should also be changed to use mysqli instead, but i've been lazy =p 并且也应该改为使用mysqli,但是我一直很懒= p

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM