Elgg  Version 3.0
DatabaseQueue.php
Go to the documentation of this file.
1 <?php
2 
3 namespace Elgg\Queue;
4 
16 class DatabaseQueue implements \Elgg\Queue\Queue {
17 
19  protected $name;
20 
22  protected $db;
23 
25  protected $workerId;
26 
33  public function __construct($name, \Elgg\Database $db) {
34  $this->db = $db;
35  $this->name = $name;
36  $this->workerId = md5(microtime() . getmypid());
37  }
38 
42  public function enqueue($item) {
43  $prefix = $this->db->prefix;
44 
45  $query = "INSERT INTO {$prefix}queue
46  (name, data, timestamp)
47  VALUES
48  (:name, :data, :timestamp)";
49  $params = [
50  ':name' => $this->name,
51  ':data' => serialize($item),
52  ':timestamp' => time(),
53  ];
54  return $this->db->insertData($query, $params) !== false;
55  }
56 
60  public function dequeue() {
61  $prefix = $this->db->prefix;
63  $worker_id = $this->workerId;
64 
65  $update = "UPDATE {$prefix}queue
66  SET worker = :worker
67  WHERE name = :name AND worker IS NULL
68  ORDER BY id ASC LIMIT 1";
69  $update_params = [
70  ':worker' => $worker_id,
71  ':name' => $name,
72  ];
73  $num = $this->db->updateData($update, true, $update_params);
74  if ($num !== 1) {
75  return;
76  }
77 
78  $select = "SELECT data
79  FROM {$prefix}queue
80  WHERE worker = :worker
81  AND name = :name";
82  $select_params = [
83  ':worker' => $worker_id,
84  ':name' => $name,
85  ];
86  $obj = $this->db->getDataRow($select, null, $select_params);
87  if (empty($obj)) {
88  return;
89  }
90 
91  $delete = "DELETE FROM {$prefix}queue
92  WHERE name = :name
93  AND worker = :worker";
94  $delete_params = [
95  ':worker' => $worker_id,
96  ':name' => $name,
97  ];
98  $this->db->deleteData($delete, $delete_params);
99 
100  return unserialize($obj->data);
101  }
102 
106  public function clear() {
107  $prefix = $this->db->prefix;
108 
109  $sql = "DELETE FROM {$prefix}queue
110  WHERE name = :name";
111  $params = [
112  ':name' => $this->name,
113  ];
114 
115  $this->db->deleteData($sql, $params);
116  }
117 
121  public function size() {
122  $prefix = $this->db->prefix;
123 
124  $sql = "SELECT COUNT(id) AS total
125  FROM {$prefix}queue
126  WHERE name = :name";
127  $params = [
128  ':name' => $this->name,
129  ];
130 
131  $result = $this->db->getDataRow($sql, null, $params);
132  return (int) $result->total;
133  }
134 }
__construct($name,\Elgg\Database $db)
Create a queue.
$query
Definition: groups.php:8
$params
Saves global plugin settings.
Definition: save.php:13
if(!$items) $item
Definition: delete.php:13
The Elgg database.
Definition: Database.php:21
clear()
{Clear all items from the queue.void}
$delete
Queue interface.
Definition: Queue.php:16
dequeue()
{Remove an item from the queue.mixed}
FIFO queue that uses the database for persistence.
Configuration exception.
size()
{Get the size of the queue.int}
enqueue($item)
{Add an item to the queue.Item to add to queue bool}
$site name