我正在开发一个web应用程序,该应用程序允许用户登录并进行管理员安排的考试。我有一个"累积"函数,一旦所有用户完成测试并更新数据库(根据一些逻辑),它就会自动运行。
我知道我可以使用数据库来存储现在正在进行测试的用户,并相应地运行逻辑,但我有兴趣知道这是否可以由单例类完成。
我的代码:
class ScoreBoard{
var $current;
private static $board=NULL;
// private static $current=0;
private function __construct() {
$this->current=0;
}
static function scoreboard(){
if(!self::$board){
self::$board= new ScoreBoard();
$this->log("Created new");
// return self::$board;
}
return self::$board;
}
function add(){
$this->current+=1;
$this->log("add ".$this->current);
}
function subtract(){
$this->current-=1;
$this->log("subtract ".$this->current);
// file_put_contents("scoreboard.txt",self::$current);
if($this->current<0)
$this->current=0;
if($this->current<=0)
{
$this->accumulate();
self::$board=NULL;
}
}
}
在startExam.php
文件中,我将此函数调用为:
$scoreboard= ScoreBoard::scoreboard();
$scoreboard->add();
做
$scoreboard= ScoreBoard::scoreboard();
$scoreboard->subtract();
当考试结束时。因此,当每个用户开始检查时,应该调用singleton对象add
函数,而当他结束检查时,则应该调用subtract
函数。但由于某种原因,这似乎不起作用,$current
从未超过1。
请告诉我我想做的事情是否可行。如果有更好的方法来实现我想做的事情,谢谢。
您可以使用Memcached
来实现这一点-
然后,您的构造函数将如下所示:
$this->memcache = new Memcached();
$this->memcache->addServer("127.0.0.1", "11211") // I think that's the right port for default.
$this->current = $this->memcache->get("current");
但你可以通过将值存储在文件中来实现同样的逻辑,这会更容易。。。