|
1
|
|
|
<?php |
|
2
|
|
|
namespace Ackintosh\Snidel; |
|
3
|
|
|
|
|
4
|
|
|
use Ackintosh\Snidel\IpcKey; |
|
5
|
|
|
|
|
6
|
|
|
class TaskQueue |
|
7
|
|
|
{ |
|
8
|
|
|
const TASK_MAX_SIZE = 1024; |
|
9
|
|
|
|
|
10
|
|
|
private $queuedCount = 0; |
|
11
|
|
|
private $dequeuedCount = 0; |
|
12
|
|
|
|
|
13
|
|
|
public function __construct($ownerPid) |
|
14
|
|
|
{ |
|
15
|
|
|
$this->ownerPid = $ownerPid; |
|
|
|
|
|
|
16
|
|
|
$this->ipcKey = new IpcKey($ownerPid, 'snidel_task_' . uniqid((string) mt_rand(1, 100), true)); |
|
|
|
|
|
|
17
|
|
|
$this->id = msg_get_queue($this->ipcKey->generate()); |
|
|
|
|
|
|
18
|
|
|
} |
|
19
|
|
|
|
|
20
|
|
|
/** |
|
21
|
|
|
* @param \Ackintosh\Snidel\Task $task |
|
22
|
|
|
* @return void |
|
23
|
|
|
* @throws RuntimeException |
|
24
|
|
|
*/ |
|
25
|
|
|
public function enqueue($task) |
|
26
|
|
|
{ |
|
27
|
|
|
$this->queuedCount++; |
|
28
|
|
|
|
|
29
|
|
|
if (!msg_send($this->id, 1, $task->serialize())) { |
|
30
|
|
|
throw new RuntimeException('failed to enqueue task.'); |
|
31
|
|
|
} |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
|
|
/** |
|
35
|
|
|
* @return \Ackintosh\Snidel\Task |
|
36
|
|
|
* @throws \RuntimeException |
|
37
|
|
|
*/ |
|
38
|
|
View Code Duplication |
public function dequeue() |
|
|
|
|
|
|
39
|
|
|
{ |
|
40
|
|
|
$this->dequeuedCount++; |
|
41
|
|
|
$msgtype = $message = null; |
|
42
|
|
|
$success = msg_receive($this->id, 1, $msgtype, self::TASK_MAX_SIZE, $message); |
|
43
|
|
|
|
|
44
|
|
|
if (!$success) { |
|
45
|
|
|
throw new \RuntimeException('failed to dequeue task'); |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
$task = unserialize($message); |
|
49
|
|
|
return $task->unserialize(); |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
public function queuedCount() |
|
53
|
|
|
{ |
|
54
|
|
|
return $this->queuedCount; |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
public function dequeuedCount() |
|
58
|
|
|
{ |
|
59
|
|
|
return $this->dequeuedCount; |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
|
|
public function __destruct() |
|
63
|
|
|
{ |
|
64
|
|
|
if ($this->ipcKey->isOwner(getmypid())) { |
|
65
|
|
|
$this->ipcKey->delete(); |
|
66
|
|
|
return msg_remove_queue($this->id); |
|
67
|
|
|
} |
|
68
|
|
|
}// @codeCoverageIgnore |
|
69
|
|
|
} |
|
70
|
|
|
|
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: