我试图改编我的一个类来处理存储在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)搜索数据库中的记录,这将需要一个传递给构造函数的变量。更糟的是,这个参数必须能够在循环中改变。例如,列出所有事件的页面必须在遍历每条记录的循环中使用此类,因此它可以检索数组来处理它,然后在表/ fullcalendar中显示它,然后重复该过程以获取下一个事件。我已经把我到目前为止的代码放在下面。它不完整(有些变量没有被重新命名为男性和女性等),可能是完全错误的,但它会给你一个基础来解释。
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框架通常所做的事情,所以您可以从使用MVC框架中受益。 – apokryfos
如果我这样做,我会需要构造/毁灭类?或者我可以使用destruct来返回我想要更改的字符串。这听起来像没有课程的痛苦,如果我这样做,我可能不会使用课程,因为我认为代码不会重复太多。 –
这个问题正在变成“到OOP或不OOP”。这真的取决于你。我只是说通常做什么。 – apokryfos