【发布时间】:2017-02-09 07:28:49
【问题描述】:
我正在尝试调整我的一个类来处理存储在 JSON 文件中的事件的标签。您可以创建标签、删除标签、恢复标签、查看标签等。在下面这个库的代码中,您可以看到我在构造函数期间从文件中检索数组,因此我使用它并在整个类的函数中操作它.
class tagHandler {
private $tagsFile = "/home/thomassm/public_html/functions/php/tags.json";
private $LstTags;
private $LstReturn;
function __construct() {
$this->LstTags = array();
if(!file_exists ($this->tagsFile)){
$fHND = fopen($this->tagsFile, "w");
$tmpArray = array(array("EID","EName","EColor", "EDel"));
fwrite($fHND, json_encode($tmpArray));
fclose($fHND);
}
$encodedInput = file ($this->tagsFile);
$this->LstTags = json_decode($encodedInput[0], true);
if(!$this->LstTags) $this->LstTags = array();
}
function __destruct(){
$this->update();
}
public function update(){
$this->LstTags = array_values($this->LstTags);
$fHND = fopen($this->tagsFile, "w");
fwrite($fHND, json_encode($this->LstTags));
fclose($fHND);
//empty memory region
$this->LstTags = array();
$encodedInput = file ($this->tagsFile);
$this->LstTags = json_decode($encodedInput[0], true);
}
//More functions that use the collected array here.
我正在尝试调整课程以应对报名参加我的活动的人。每个事件在我的数据库中都有一条记录,该记录将为一组注册的男性和注册的女性存储一个字段。我希望构造函数类从记录中获取数组,以便可以像上一个类一样操作它们。问题是要获取数组,我必须在数据库中搜索具有事件 ID (EID) 的记录,这需要将变量传递给构造函数。更糟糕的是,这个参数必须能够在一个循环中改变。例如,列出所有事件的页面将不得不在遍历每条记录的循环中使用此类,因此它可以检索数组以对其进行操作,然后将其显示在表格/完整日历中,然后重复该过程以获取下一个事件.我已将到目前为止的代码放在下面。它不完整(一些变量没有重命名为男性和女性等)并且可能完全错误,但它会给你一个解释的基础。
class signupHandler {
private $LstMaleS;
private $LstFemaleS;
private $LstReturn;
function __construct($IntEID) {
$this->LstTags = array();
$StrQuery = "SELECT MaleS, FemaleS FROM tblEvents WHERE EID = ?";
if ($statement = TF_Core::$MySQLi->DB->prepare($StrQuery)) {
$statement->bind_param('s',$IntEID);
$statement->execute ();
$results = $statement->get_result ();
}
$this->LstTags = json_decode($encodedInput[0], true);
if(!$this->LstTags) $this->LstTags = array();
}
谢谢, 汤姆
【问题讨论】:
-
我要做的是在
signupHandler的构造函数中传递数据库结果数组。您可以在类外查询并初始化类。这样,您还可以使用该类来保存尚未在数据库中的新条目,然后有一个方法来保存该条目。这是 MVC 框架通常会做的事情,因此您可以从使用其中受益。 -
如果我这样做了,我需要构造函数/破坏类吗?或者我可以使用 destruct 来返回我猜想的更改后的字符串。如果没有课程,这听起来确实很痛苦,如果我这样做,我也可能不使用整个课程,因为我认为代码不会重复太多。
-
这个问题正在变成“to OOP or to not OOP”。这真的取决于你。我只是说通常会做什么。