Guest User

Untitled

a guest
Apr 20th, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.36 KB | None | 0 0
  1. <?php
  2. class SharedArray implements ArrayAccess, IteratorAggregate, Countable {
  3. private $db = NULL;
  4. private $result;
  5.  
  6. public function __construct() {
  7. if ($this->db === NULL && $this->db = sqlite_open('shared_array.db')) {
  8. @sqlite_query(
  9. $this->db,
  10. 'CREATE TABLE shared_array
  11. (offset varchar(32) PRIMARY KEY,
  12. value text);'
  13. );
  14. }
  15. }
  16.  
  17. public function __destruct() {
  18. if ($this->db !== NULL) {
  19. sqlite_close($this->db);
  20. }
  21. $this->db = NULL;
  22. }
  23.  
  24. public function offsetExists($offset) {
  25. $result = sqlite_query(
  26. $this->db,
  27. "SELECT offset
  28. FROM shared_array
  29. WHERE offset = '$offset';"
  30. );
  31.  
  32. if ($result === FALSE) {
  33. return FALSE;
  34. } else {
  35. return TRUE;
  36. }
  37. }
  38.  
  39. public function offsetGet($offset) {
  40. return sqlite_fetch_single(
  41. sqlite_query(
  42. $this->db,
  43. "SELECT value
  44. FROM shared_array
  45. WHERE offset = '$offset';"
  46. )
  47. );
  48. }
  49.  
  50. public function offsetSet($offset, $value) {
  51. sqlite_query(
  52. $this->db,
  53. "REPLACE INTO shared_array
  54. (offset, value)
  55. VALUES ('$offset', '$value');"
  56. );
  57. }
  58.  
  59. public function offsetUnset($offset) {
  60. sqlite_query(
  61. $this->db,
  62. "DELETE FROM shared_array
  63. WHERE offset = '$offset'"
  64. );
  65. }
  66.  
  67. // wegen interface IteratorAggregate
  68. public function getIterator() {
  69. return new SharedArrayIterator($this->db);
  70. }
  71.  
  72. // wegen interface Countable
  73. public function count() {
  74. $this->result = sqlite_query($this->db, 'SELECT * FROM shared_array');
  75. return sqlite_num_rows($this->result);
  76. }
  77.  
  78. public function purge() {
  79. sqlite_query(
  80. $this->db,
  81. "DELETE FROM shared_array"
  82. );
  83. }
  84. }
  85.  
  86. class SharedArrayIterator implements Iterator {
  87. private $result;
  88. private $position;
  89.  
  90. public function __construct(&$resource) {
  91. $this->result = sqlite_query($resource, "SELECT offset, value FROM shared_array");
  92. }
  93.  
  94. public function rewind() {
  95. $this->position = 0;
  96. }
  97.  
  98. public function valid() {
  99. return $this->position < sqlite_num_rows($this->result);
  100. }
  101.  
  102. public function key() {
  103. $current = sqlite_current($this->result);
  104. return $current['offset'];
  105. }
  106.  
  107. public function current() {
  108. $current = sqlite_current($this->result);
  109. return $current['value'];
  110. }
  111.  
  112. public function next() {
  113. sqlite_next($this->result);
  114. $this->position++;
  115. }
  116. }
  117. ?>
Add Comment
Please, Sign In to add comment