name = (string)$queue_name; // Defined counter keys $this->head = $this->prefix.$this->name.'_head'; $this->tail = $this->prefix.$this->name.'_tail'; $this->key = $this->prefix.$this->name.'_'; $this->init($force_new); } /** * Initializes the queue and checks for counter integrity * @access private * @param boolean $force_new * @return boolean */ private function init($force_new=FALSE) { if($force_new) { // Force new queue by resettings counters apc_store($this->head, 0); apc_store($this->tail, 0); }else{ // Check head counter $success = FALSE; $val_head = apc_fetch($this->head, $success); if(!$success) { apc_store($this->head, 0); } // Check tail counter $success = FALSE; $val_tail = apc_fetch($this->tail, $success); if(!$success) { apc_store($this->tail, 0); } // Check counter integrity if($val_head < $val_tail) { // Force new queue $this->init(TRUE); } } return TRUE; } /** * Adds a value to queue * @param mixed $value */ public function add($value) { $id = apc_fetch($this->head)+1; apc_store($this->head, $id); apc_store($this->key.$id, $value); return TRUE; } /** * Fetches next value from queue. FALSE if empty. * @return mixed */ public function get() { // Check length if($this->length() < 1) { // Reset counters if queue is empty $this->init(TRUE); return FALSE; } $id = apc_fetch($this->tail)+1; apc_store($this->tail, $id); return apc_fetch($this->key.$id); } /** * Returns queue length * @return integer */ public function length() { $head = apc_fetch($this->head); $tail = apc_fetch($this->tail); $length = $head - $tail; return ($length >= 0) ? $length : 0 ; } } // Check if APC has some memory left // var_dump(apc_sma_info()); // Example: /* $q = new apc_queue('test', isset($_GET['force'])); echo "LENGTH: ", $q->length(), "\nSTORE: "; for($i=0; $i<10; ++$i) { $rand = rand(0,9); echo $rand,','; $q->add($rand); } echo "\nLENGTH: ", $q->length(), "\nFETCH: "; while(($g = $q->get()) !== FALSE) { echo $g,','; } echo "\nLENGTH: ", $q->length(); */