gpt4 book ai didi

php - 当有 __construct() 元素时将类转换为函数

转载 作者:可可西里 更新时间:2023-10-31 22:13:27 26 4
gpt4 key购买 nike

我正在(不断地)学习 PHP,不久前我创建了一个处理翻译的类。我要emulate gettext但从数据库中获取翻译后的字符串。但是,现在我再次看到它,我不喜欢这样,作为一个类,要调用它我需要使用 $Translate->text('String_keyword');。我不喜欢必须使用 $T->a('String_keyword'); 因为那完全不直观。

我一直在思考如何使用简单的 _('String_keyword') gettext 样式来调用它,但是根据我从 SO 中学到的知识,我还没有'能够找到一个'伟大'的方法来完成这个。我需要以某种方式将默认语言传递给函数,我不想每次调用它时都传递它,因为它会是 _('String_keyword', $User->get('Language')))。我也不想在 _() 函数中包含用户检测脚本,因为它只需要运行一次而不是每次都运行。

最简单的方法是使用 GLOBALS,但我在这里了解到它们是完全禁止的(这可能是我 can use them? 的唯一情况),然后我想到 DEFINE具有用户语言的变量,如 define ( USER_LANGUAGE , $User->get('Language') ),但它似乎与全局相同。这些是我能看到的 2 个主要选项,我知道还有一些其他方法,例如依赖注入(inject),但它们似乎为如此简单的请求增加了太多的复杂性,我还没有时间深入研究它们。

我正在考虑先创建一个包装器来测试它。像这样:

function _($Id, $Arg = null)
{
$Translate = new Translate (USER_LANGUAGE);
return $Translate -> text($Id, $Arg)
}

这是翻译代码。之前会检测语言并在创建对象时将其传递给对象。

// Translate text strings
// TO DO: SHOULD, SHOULD change it to PDO! Also, merge the 2 tables into 1
class Translate
{
private $Lang;

function __construct ($Lang)
{
$this->Lang = $Lang;
}

// Clever. Adds the translation so when codding I don't get annoyed.
private function add ($Id, $Text)
{
$sql="INSERT INTO htranslations (keyword, en, page, last) VALUES ('$Id', '$Text', '".$_SERVER['PHP_SELF']."', now())";

mysql_query($sql);
}

private function retrieve ( $Id )
{
$table = is_int ($Id) ? "translations" : "htranslations"; // A small tweak to support the two tables, but they should be merged.
$results = mysql_query ("SELECT ".mysql_real_escape_string($this->Lang)." FROM ".$table." WHERE keyword='".mysql_real_escape_string($Id)."'");
$row = mysql_fetch_assoc ($results);
return mysql_num_rows ($results) ? stripslashes ($row[$this->Lang]) : null;
}

// If needed to insert a name, for example, pass it in the $Arg
public function text($Id, $Arg = null)
{
$Text = $this->retrieve($Id);
if (empty($Text))
{
$Text = str_replace("_", " ", $Id); // If not found, replace all "_" with " " from the input string.
$this->add($Id, $Text);
}
return str_replace("%s", $Arg, $Text); // Not likely to have more than 2 variables into a single string.
}
}

您将如何以一种适当而简单(对于编码)的方式完成此任务?所提出的任何方法是否有效,或者您能否提供更好的方法?

最佳答案

如果问题只是这样

$Translate->text('String_keyword');

感觉太长了,那就考虑通过实现__invoke把Translate对象变成Functor :

class Translate
{
// all your PHP code you already have

public function __invoke($keyword, $Arg = null)
{
return $this->text($keyword, $Arg)
}
}

然后您可以使用所有必需的依赖项和设置定期实例化对象并调用它:

$_ = new Translate(/* whatever it needs */);
echo $_('Hallo Welt');

这不会像您当前考虑通过包装函数或其他地方建议的注册表/单例解决方案那样引入与全局范围相同数量的耦合和摆弄。唯一的缺点是对象变量的非语音命名为 $_()

关于php - 当有 __construct() 元素时将类转换为函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13221863/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com