6 * Asynchronnous resource handling, optionally (ab)using ticks
13 * $conn = new \pq\Connection;
14 * $conn->execAsync("SELECT * FROM foo", function ($rs) {
18 * $ticker = new \atick\Ticker;
19 * $ticker->register();
20 * $ticker->read($conn->socket, function($fd) use ($conn) {
29 * while (count($ticker));
33 * And an example without ticks:
36 * $conn = new \pq\Connection;
37 * $conn->execAsync("SELECT * FROM foo", function ($r) {
41 * $ticker = new \atick\Ticker;
42 * $ticker->read($conn->socket, function($fd) use ($conn) {
55 class Ticker
implements \Countable
60 protected $read = array();
65 protected $write = array();
68 * Register the ticker as tick function
69 * @return \atick\Ticker
72 register_tick_function(array($this, "__invoke"));
77 * Unregister the ticker as tick function
78 * @return \atick\Ticker
80 function unregister() {
81 unregister_tick_function(array($this, "__invoke"));
86 * The tick handler; calls atick\Ticker::wait(0)
90 return $this->wait(0);
94 * Wait for read/write readiness on the watched fds
95 * @param float $timeout
96 * @return int count of wached fds
98 function wait($timeout = 1) {
99 $r = $w = $e = array();
100 foreach ($this->read
as $s) {
103 foreach ($this->write
as $s) {
107 $u = (int) (($timeout - $s) * 1000000);
108 if (($r ||
$w) && stream_select($r, $w, $e, $s, $u)) {
110 if ($this->read
[(int)$s][1]($s)) {
111 unset($this->read
[(int)$s]);
115 if ($this->write
[(int)$s][1]($s)) {
116 unset($this->write
[(int)$s]);
120 return $this->count();
124 * @implements \Countable
128 return count($this->read
) +
count($this->write
);
132 * Attach a read handler; let the callback return true, to stop watching the fd.
133 * @param resource $fd
134 * @param callable $cb
135 * @return \atick\Ticker
137 function read($fd, callable
$cb) {
138 $this->read
[(int)$fd] = array($fd, $cb);
143 * Attach a write handler; let the callback return true, to stop watching the fd.
145 * @param callable $cb
146 * @return \atick\Ticker
148 function write($fd, callable
$cb) {
149 $this->write
[(int)$fd] = array($fd, $cb);