Created
March 15, 2018 13:47
-
-
Save 1d10t/9c1ae4b577eca7b6cb98b12f95df61b2 to your computer and use it in GitHub Desktop.
shared memory array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
$port = 9050; | |
$proxy_score = new shmop_arr('x', 4*1024); | |
$proxy_score[$port] = isset($proxy_score[$port]) ? $proxy_score[$port]+1 : 1; | |
print_r($proxy_score->__toArray()); | |
*/ | |
class shmop_arr | |
implements ArrayAccess | |
{ | |
private $shmop_key; | |
private $shmop_id; | |
private $shmop_block_size = 2048; | |
private $_data = array(); | |
private function _open(){ | |
if(!$this->shmop_id) | |
$this->shmop_id = shmop_open($this->shmop_key, 'c', 0755, $this->shmop_block_size); | |
return $this->shmop_id; | |
} | |
private function _close(){ | |
if($this->shmop_id) shmop_close($this->shmop_id); | |
$this->shmop_id = null; | |
} | |
private function _read(){ | |
$this->_open(); | |
$this->_data = array(); | |
$size = shmop_size($this->shmop_id); | |
$d = $size ? shmop_read($this->shmop_id, 0, $size) : ''; | |
$this->_close(); | |
if(!strlen($d)){ | |
return; | |
} | |
$d = substr($d, 0, strpos($d, "\0")); | |
if(strlen($d)){ | |
$this->_data = unserialize($d); | |
} | |
} | |
private function _write(){ | |
$this->_open(); | |
shmop_write($this->shmop_id, serialize($this->_data)."\0", 0); | |
$this->_close(); | |
} | |
public function __construct($project = "\0", $shmop_block_size = null){ | |
$this->shmop_key = ftok(__FILE__, $project); | |
if(isset($shmop_block_size)) $this->shmop_block_size = $shmop_block_size; | |
} | |
public function __get($key){ | |
$this->_read(); | |
return isset($this->_data[$key]) ? $this->_data[$key] : null; | |
} | |
public function __set($key, $value){ | |
$this->_read(); | |
$this->_data[$key] = $value; | |
$this->_write(); | |
} | |
public function __isset($key){ | |
$this->_read(); | |
return isset($this->_data[$key]); | |
} | |
public function __unset($key){ | |
$this->_read(); | |
unset($this->_data[$key]); | |
$this->_write(); | |
} | |
public function __toArray(){ | |
$this->_read(); | |
return $this->_data; | |
} | |
public function __toString(){ | |
return serialize($this->__toArray()); | |
} | |
public function offsetExists($offset){ | |
return $this->__isset($offset); | |
} | |
public function offsetGet($offset){ | |
return $this->__get($offset); | |
} | |
public function offsetSet($offset, $value){ | |
return $this->__set($offset, $value); | |
} | |
public function offsetUnset($offset){ | |
return $this->__unset($offset, $value); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment