PHP a custom SUPERGLOBAL array question
I was reading around, and I know it might be impossible to accomplish as I wished it w开发者_运维知识库ould be but I am hoping there is a way, so here goes..
I have ID's of users and I have a count for each. I would like to be able to store those values in machine memory, and update the DB only once in a while, but absolutley not constantly. The page is being accessed from many users of course, and I want the array to stay relevant for each user, and update as necessary. (That's another reason I don't want to use the DB. Updates take time with indexed columns, right?)
an array such as : $my_superglobal_arr = ('1'=>304,'2'=>763,'6'=>12,'13'=>96); would have been perfect.
Any suggestions ?
Thanks !
Updates take time with indexed columns, right?
Right. However, it depends. I'd strongly suggest you to go for the database first, get practical experience with updates and stuff, learn what particular amount of users you can call "many". And only then decide, if you really need your unusual setup, is it really necessary or just imaginary fantasies.
Reading your other questions I only can say that to learn SQL first is a must.
You need to couple ArrayAccess
with APC caching abilities and employ a Singleton
pattern.
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() {}
}
Usage:
$user_counter = UserCounter::getInstance();
$user_counter[1] = $user_counter[1] + 1;
var_dump($user_counter[1]);
Output on the first request:
int(1)
On the second:
int(2)
When you need to save these counters in a database:
$user_counter = UserCounter::getInstance();
foreach ($users as $user_id) {
store_counter_in_db($user_id, $user_counter[$user_id]);
}
Note: there is a bug which may prevent you from incrementing a single counter during single request in certain versions of APC. Incrementing in subsequent requests is not a problem, as far a I can tell.
This isn't something PHP offers natively. You're best bet is to store the data in a memory based key/value store. PHP natively supports memcached which most hosts offer. You can also take a look at MongoDB and Redis
精彩评论