1
0
mirror of https://github.com/danog/postgres.git synced 2024-12-11 17:09:47 +01:00
postgres/examples/listen.php

43 lines
1.3 KiB
PHP
Raw Normal View History

2016-09-19 18:12:32 +02:00
#!/usr/bin/env php
<?php
require dirname(__DIR__) . '/vendor/autoload.php';
use Amp\Postgres;
use Amp\Loop;
2016-09-19 18:12:32 +02:00
Loop::run(function () {
$pool = Postgres\pool('host=localhost user=postgres');
$channel = "test";
2016-09-19 18:12:32 +02:00
/** @var \Amp\Postgres\Listener $listener */
$listener = yield $pool->listen($channel);
printf("Listening on channel '%s'\n", $listener->getChannel());
2016-09-19 18:12:32 +02:00
2017-01-18 19:52:40 +01:00
Loop::delay(3000, Amp\wrap(function () use ($listener) { // Unlisten in 3 seconds.
printf("Unlistening from channel '%s'\n", $listener->getChannel());
2017-01-18 19:52:40 +01:00
return $listener->unlisten();
}));
2016-09-19 18:12:32 +02:00
2017-01-18 19:52:40 +01:00
Loop::delay(1000, Amp\wrap(function () use ($pool, $channel) {
return $pool->notify($channel, "Data 1"); // Send first notification.
}));
2017-01-18 19:52:40 +01:00
Loop::delay(2000, Amp\wrap(function () use ($pool, $channel) {
return $pool->notify($channel, "Data 2"); // Send second notification.
}));
2017-01-18 19:52:40 +01:00
while (yield $listener->advance()) {
2016-09-19 18:12:32 +02:00
/** @var \Amp\Postgres\Notification $notification */
$notification = $listener->getCurrent();
printf(
"Received notification from PID %d on channel '%s' with payload: %s\n",
2016-09-19 18:12:32 +02:00
$notification->pid,
$notification->channel,
$notification->payload
);
}
});