4

Choices

I am learning OOP PHP, but some things are really confusing. I have a general idea of where to use static methods, but I'm not sure if here it's a good idea.

My questions is about which is actually the best approach for the specific problem I am facing (described below). The general guidelines I've found online didn't help for this specific problem. Here is what I thought (from more likely to be correct to less):

  • Extend the Language class, create a single object (that gets the language in the initialization) and call a method with the $id that would return the translated string.

  • Merge both classes into one. The language would be found when initialized and a method called when needed. But it would behave a little as a God object.

  • Make the Language class static. Therefore I would be able to use it from within the Text. I would create a Text instance and call a method with different $id. Similar to using it with globals. There's almost no other place where I'd need to use the Language class.

  • Extend the Language class with Text, create an object for each translation. This would probably create too much overhead.

  • Not do anything. It's tempting (don't fix it if it's not broken), but I intend to start developing with someone else soon, so clean and clear code is needed.

Code

Now the simple class:

class Language
  {
  public $Lang;
  public function __construct()
    {
    if ( !empty($_POST['lang']) )    // If the user tries to change the language
      {
      $this->Lang = mysql_real_escape_string($_POST['lang']);  // Assign the language to variable.
      $_SESSION['lang'] = $this->Lang;      //Sets the session to have that language.
      if ($_SESSION['logged']==1)          // If user is logged
        {
        $User=$_SESSION['user'];
        mysql_query("UPDATE users SET lang='$this->Lang' WHERE email='$User'") or die(mysql_error());  // Saves the language into user preferences
        }
      }
    else      // If no request is done.
      {
      if ($_SESSION['logged']==1)    // DO. Check for user's language
        {
        $User=mysql_real_escape_string($_SESSION['user']);
        $result=mysql_query("SELECT * FROM users WHERE email='$User'");
        $row=mysql_fetch_array($result);
        $this->Lang=$row['lang'];
        }
      else
        if ( !empty ($_SESSION['lang']))  // If the session exists (not empty)
          $this->Lang = $_SESSION['lang'];  // Assign the session language to variable.
        else          // If it doesn't exist
          $this->Lang = substr ($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);  // Get it from the browser
      }
    //If the language is not supported (or still doesn't exist), then put "en" as default. Supported so far: en, es.
    if ( $this->Lang !== "en" && $this->Lang !== "es") $this->Lang="en";
    }
  }

I have few methods inside this class, but that's the only relevan code here. So I initialize it with $Language=new Language; and then use $Language->Lang; to obtain the user language. So far so good.

This is the function I want to reconvert to a class. It gets an integer or a string, searches it as an id with mysql and returns a translated string in the right language. Now, how do I achieve this? Here it's the text() function. It was used with globals, which is apparently a really bad practice.

function text($Id)
    {
    // Already defined and tested that are valid (sql injection avoided also)
    global $Lang;
    global $Url;
    global $Version;
    global $Banner;
    if (!empty($Url["folder"])) $FullUrl = "/".$Url["folder"]."/";
      else $FullUrl="/";
    if (!is_int($Id)) $Id = mysql_real_escape_string( $Id );

    $numargs = func_num_args();  // Get the number of arguments that are being passed.
    if ($numargs == 2)  // If there are actually two
      $Var=func_get_arg(1);  // Set $Var with the second value (1).

    if (is_int($Id))  // If a number is being passed
      {
        // Add AND page='$FullUrl' to control scope of the strings translated
      $results = mysql_query("SELECT * FROM translations WHERE id='$Id'") or die ('Could not query:' . mysql_error());
      $row = mysql_fetch_assoc($results);
      if (!empty($row[$Lang]) && !isset($Var)) echo stripslashes($row[$Lang]);  // If there is some, echo it
        elseif ($Var==1) return stripslashes($row[$Lang]); // If it is required to be a returned string, send it.
      else error($FullUrl,$Lang);  // If there is nothing there, calls error function.
      }
    else  // If a string is being passed
      {
      $results = mysql_query("SELECT * FROM htranslations WHERE keyword='$Id'") or die ('Could not query:' . mysql_error());
      $row = mysql_fetch_assoc($results);

      if (!empty($row[$Lang]) && !isset($Var)) echo stripslashes($row[$Lang]);  // If it exists in the table, echo it
      elseif (!empty($row[$Lang]) && isset($Var)) return stripslashes($row[$Lang]);
      else  // Else (it doesn't exist)
        {
        $Id = str_replace("_", " ", $Id);  // Replace the "_" with " "
        if (!isset($Var))
          {
          echo $Id;  // Echo the passed string with spaces
          }
        else return $Id;

        $Banner="There might be some misstranslation. Please report if needed.";
        }
      }
    }
4

1 回答 1

1

所以 text 函数有很多副作用;意思是,它涉及很多东西,有时会返回,有时会打印到标准输出。这通常不好,因为它很难调试、单元测试和重构

我会选择选项 2:将两个类合并为一个。初始化时会找到该语言,并在需要时调用一个方法。

下面是我将如何实现这一点(我尽可能多地保持代码完整,以便您了解 OOP 方面发生了什么变化。还有很多其他的事情我会改变;主要是其他人已经评论过的内容以及不从内部打印任何内容方法。让方法返回一些东西而不是从内部修改应用程序状态是一种很好的做法

我改变的事情:

文本函数实际上在特定时间更改了一个全局变量 ($Banner),使用两个全局变量 ($Url) 和 ($Lang 它实际上来自语言对象) 然后从数据库返回一个 Id 或可能打印到标准输出。

由于将文本函数移到 Language 类中,我将全局 $Lang 变量转换为使用 Language 类的实例变量 $Lang

$Url 方法仅在 text 函数中使用,因此可以传递给 text 方法

全局变量 $Banner 实际上是由我认为不好的副作用的文本函数设置的。我决定替换这段代码:

$Banner = "可能有一些翻译错误。如果需要请报告。";

返回假。

这样,如果 text 方法返回 false,您可以将 $Banner 变量设置为“可能有一些误译。如果需要,请报告。” 这是从对象外部完成的。

另外,我从文本函数中删除了全局变量 $Version,因为它没有在函数中使用

我还建议让 text 方法只返回而不打印到标准输出。错译拼写错误。应该是误译。

我希望这有帮助...

<?php

class Language {

    public $Lang;

    public function __construct() {
        if (!empty($_POST['lang'])) {    // If the user tries to change the language
            $this->Lang = mysql_real_escape_string($_POST['lang']);  // Assign the language to variable.
            $_SESSION['lang'] = $this->Lang;      //Sets the session to have that language.
            if ($_SESSION['logged'] == 1) {          // If user is logged
                $User = $_SESSION['user'];
                mysql_query("UPDATE users SET lang='$this->Lang' WHERE email='$User'") or die(mysql_error());  // Saves the language into user preferences
            }
        } else {      // If no request is done.
            if ($_SESSION['logged'] == 1) {    // DO. Check for user's language
                $User = mysql_real_escape_string($_SESSION['user']);
                $result = mysql_query("SELECT * FROM users WHERE email='$User'");
                $row = mysql_fetch_array($result);
                $this->Lang = $row['lang'];
            } else
            if (!empty($_SESSION['lang']))  // If the session exists (not empty)
                $this->Lang = $_SESSION['lang'];  // Assign the session language to variable.
            else          // If it doesn't exist
                $this->Lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);  // Get it from the browser
        }
        //If the language is not supported (or still doesn't exist), then put "en" as default. Supported so far: en, es.
        if ($this->Lang !== "en" && $this->Lang !== "es")
            $this->Lang = "en";
    }

    public function text($Id, $Url) {
        // Already defined and tested that are valid (sql injection avoided also)
        if (!empty($Url["folder"]))
            $FullUrl = "/" . $Url["folder"] . "/";
        else
            $FullUrl = "/";
        if (!is_int($Id))
            $Id = mysql_real_escape_string($Id);

        $numargs = func_num_args();  // Get the number of arguments that are being passed.
        if ($numargs == 2)  // If there are actually two
            $Var = func_get_arg(1);  // Set $Var with the second value (1).

        if (is_int($Id)) {  // If a number is being passed
            // Add AND page='$FullUrl' to control scope of the strings translated
            $results = mysql_query("SELECT * FROM translations WHERE id='$Id'") or die('Could not query:' . mysql_error());
            $row = mysql_fetch_assoc($results);
            if (!empty($row[$this->Lang]) && !isset($Var)) {
                echo stripslashes($row[$this->Lang]);  // If there is some, echo it
            } elseif ($Var == 1) {
                return stripslashes($row[$this->Lang]); // If it is required to be a returned string, send it.
            } else {
                error($FullUrl, $this->Lang);  // If there is nothing there, calls error function.
            }
        } else {  // If a string is being passed
            $results = mysql_query("SELECT * FROM htranslations WHERE keyword='$Id'") or die('Could not query:' . mysql_error());
            $row = mysql_fetch_assoc($results);

            if (!empty($row[$this->Lang]) && !isset($Var)) {
                echo stripslashes($row[$this->Lang]);  // If it exists in the table, echo it
            } elseif (!empty($row[$this->Lang]) && isset($Var)) {
                return stripslashes($row[$this->Lang]);
            } else {  // Else (it doesn't exist)
                $Id = str_replace("_", " ", $Id);  // Replace the "_" with " "
                if (!isset($Var)) {
                    echo $Id;  // Echo the passed string with spaces
                } else {
                    return $Id;
                }

                return false;
            }
        }
    }

}

?>
于 2012-09-01T14:42:01.547 回答