加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 我应该使用静态方法和属性来检测语言并翻译文本吗?

发布时间:2020-12-13 22:44:48 所属栏目:PHP教程 来源:网络整理
导读:选择 我正在学习OOP PHP,但有些事情真的令人困惑.我对使用静态方法的地方有一个大概的了解,但我不确定这是不是一个好主意. 我的问题是关于哪个实际上是我面临的具体问题的最佳方法(如下所述).我在网上找到的一般指导原则对这个具体问题没有帮助.这是我的想法
选择

我正在学习OOP PHP,但有些事情真的令人困惑.我对使用静态方法的地方有一个大概的了解,但我不确定这是不是一个好主意.

我的问题是关于哪个实际上是我面临的具体问题的最佳方法(如下所述).我在网上找到的一般指导原则对这个具体问题没有帮助.这是我的想法(从更可能是正确到更少):

>扩展Language类,创建一个单独的对象(在初始化中获取语言)并调用一个带有$id的方法,该方法将返回已翻译的字符串.
>将两个类合并为一个.初始化时会找到该语言,并在需要时调用该方法.但它会表现为God object.
>使语言类静态.因此我可以在Text中使用它.我将创建一个Text实例并调用具有不同$id的方法.与使用全局变量类似.几乎没有其他地方我需要使用语言课程.
>使用Text扩展Language类,为每个翻译创建一个对象.这可能会产生太多的开销.
>什么都不做.这很诱人(如果它没有被破坏就不要修复它),但我打算很快就和别人一起开发,所以需要干净清晰的代码.

现在简单的类:

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'],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";
    }
  }

我在这个类中有很少的方法,但这是这里唯一的相关代码.所以我用$Language = new Language初始化它;然后使用$Language-> Lang;获取用户语言.到现在为止还挺好.

这是我想要重新转换为类的函数.它获取整数或字符串,使用mysql将其作为id进行搜索,并以正确的语言返回已翻译的字符串.现在,我该如何实现这一目标?这是text()函数.它与全局变量一起使用,这显然是一种非常糟糕的做法.

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.";
        }
      }
    }

解决方法

因此文本功能有很多副作用;意思是,它触动了很多
??东西,有时返回和其他时间打印的东西
??标准输出.这通常不好,因为它很难调试,单元测试
??和重构

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

下面是我将如何实现这一点(尽可能保持尽可能多的代码,以便你能理解
??关于OOP的改变是什么.我还会改变许多其他事情;大多是其他人
??已经评论过加号而不是从方法中打印任何内容.这是一个很好的做法
??让方法返回一些东西,而不是从内部修改应用程序状态

我改变的事情:

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

自从将文本函数移动到Language类后,我转换了全局$Lang
??变量以使用Language类的实例变量$Lang

$Url方法仅用于文本函数,因此可以传递给text方法

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

$Banner =“可能存在一些误解.如果需要请报告.”;

返回false.

这样,如果text方法返回false,则可以设置$Banner
??变量为“可能存在一些错误翻译.如果需要,请报告.”哪一个
??是从对象外部完成的.

此外,我从文本函数中删除了全局变量$Version,因为它未在其中使用
??功能

我还建议让文本方法只返回而不打印到
??标准输出.误译是错误的.应该是误译.

我希望这有帮助…

<?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'],2);  // Get it from the browser
        }
        //If the language is not supported (or still doesn't exist),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;
            }
        }
    }

}

?>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读