您需要夫婦ArrayAccess
與APC緩存能力,採用Singleton
模式。
class UserCounter implements ArrayAccess {
public static function getInstance()
{
static $instance;
if (!$instance) {
$instance = new self;
}
return $instance;
}
public function offsetSet($offset, $value)
{
apc_store(__CLASS__.$offset, $value);
}
public function offsetExists($offset)
{
return !!apc_fetch(__CLASS__.$offset);
}
public function offsetUnset($offset)
{
apc_delete(__CLASS__.$offset);
}
public function offsetGet($offset)
{
return apc_fetch(__CLASS__.$offset);
}
private function __construct() {}
private function __clone() {}
private function __wakeup() {}
}
用法:
int(1)
在第二:在第一次請求
$user_counter = UserCounter::getInstance();
$user_counter[1] = $user_counter[1] + 1;
var_dump($user_counter[1]);
輸出
int(2)
當你需要這些計數器在數據庫中保存:
$user_counter = UserCounter::getInstance();
foreach ($users as $user_id) {
store_counter_in_db($user_id, $user_counter[$user_id]);
}
注意:there is a bug這可能會阻止您在某些APC版本的單個請求期間遞增單個計數器。據我所知,後續請求中的增量不是問題。
全局變量是邪惡的 – zerkms
你是在談論在單個請求期間還是在多個請求期間更新數據庫? 嘗試查找Memcached或Redis,看看它是否符合法案。 – whichdan
@zerkms閱讀郵件正文,而不是標題:P –