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

44 lines
1.2 KiB
PHP
Raw Normal View History

2016-09-19 18:12:32 +02:00
#!/usr/bin/env php
<?php
2018-07-01 19:33:12 +02:00
require \dirname(__DIR__) . '/vendor/autoload.php';
2016-09-19 18:12:32 +02:00
use Amp\Loop;
2017-05-16 06:28:37 +02:00
use Amp\Postgres;
2016-09-19 18:12:32 +02:00
Loop::run(function () {
2018-10-15 17:44:40 +02:00
$config = Postgres\ConnectionConfig::fromString('host=localhost user=postgres');
2018-10-14 17:48:07 +02:00
2018-10-15 17:44:40 +02:00
$pool = Postgres\pool($config);
2017-05-16 06:28:37 +02:00
$channel = "test";
2017-05-16 06:28:37 +02:00
2016-09-19 18:12:32 +02:00
/** @var \Amp\Postgres\Listener $listener */
$listener = yield $pool->listen($channel);
2017-05-16 06:28:37 +02:00
2018-07-01 19:33:12 +02:00
\printf("Listening on channel '%s'\n", $listener->getChannel());
2017-05-16 06:28:37 +02:00
2017-05-26 21:41:02 +02:00
Loop::delay(3000, function () use ($listener) { // Unlisten in 3 seconds.
2018-07-01 19:33:12 +02:00
\printf("Unlistening from channel '%s'\n", $listener->getChannel());
2017-01-18 19:52:40 +01:00
return $listener->unlisten();
2017-05-26 21:41:02 +02:00
});
2017-05-16 06:28:37 +02:00
2017-05-26 21:41:02 +02:00
Loop::delay(1000, function () use ($pool, $channel) {
2017-01-18 19:52:40 +01:00
return $pool->notify($channel, "Data 1"); // Send first notification.
2017-05-26 21:41:02 +02:00
});
2017-05-16 06:28:37 +02:00
2017-05-26 21:41:02 +02:00
Loop::delay(2000, function () use ($pool, $channel) {
2017-01-18 19:52:40 +01:00
return $pool->notify($channel, "Data 2"); // Send second notification.
2017-05-26 21:41:02 +02:00
});
2017-01-18 19:52:40 +01:00
while (yield $listener->advance()) {
2016-09-19 18:12:32 +02:00
$notification = $listener->getCurrent();
2018-07-01 19:33:12 +02:00
\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
);
}
});