pg_get_notify

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

pg_get_notifySQL NOTIFY メッセージを取得する

説明

pg_get_notify(PgSql\Connection $connection, int $mode = PGSQL_ASSOC): array|false

pg_get_notify()は、NOTIFY SQL コマンドにより送信された通知メッセージを取得します。 通知メッセージを取得するには、LISTEN SQL コマンドを発行する必要があります。

パラメータ

connection

PgSql\Connection クラスのインスタンス。

mode

返される配列のインデックスを制御するオプションの引数です。 mode は定数で、以下の値を取ることができます。: PGSQL_ASSOC, PGSQL_NUM, PGSQL_BOTHPGSQL_NUM を使うと、配列のインデックスを数値にした配列を返します。PGSQL_ASSOC を使うと、連想配列のインデックスを返します。PGSQL_BOTH を指定すると、数値と連想配列のインデックスを両方含めた形で配列を返します。

戻り値

NOTIFY メッセージ名とバックエンドの PID を含む 配列を返します。 サーバーでサポートされている場合は、 配列にはサーバーのバージョンおよびペイロードも含まれます。 もし待ち受ける NOTIFY が存在しない場合は、 false を返します。

変更履歴

バージョン 説明
8.1.0 connection は、PgSql\Connection クラスのインスタンスを期待するようになりました。 これより前のバージョンでは、リソース を期待していました。

例1 PostgreSQL NOTIFY メッセージ

<?php
$conn
= pg_pconnect("dbname=publisher");
if (!
$conn) {
echo
"An error occurred.\n";
exit;
}

// 他のプロセスからの 'author_updated' メッセージを監視する
pg_query($conn, 'LISTEN author_updated;');
$notify = pg_get_notify($conn);
if (!
$notify) {
echo
"No messages\n";
} else {
print_r($notify);
}
?>

参考

  • pg_get_pid() - バックエンドのプロセス ID を得る

add a note add a note

User Contributed Notes 2 notes

up
5
glococo at gmail dot com
6 years ago
Instant yet Simple PHP notification with HTML5 Server-Sent Events

sse.php
<?php
$dbconn
= new PDO("pgsql:host=localhost;dbname=mydb", "pduser", "userpass");
$dbconn->exec('LISTEN "channel_name"');   // those doublequotes are very important

header("X-Accel-Buffering: no"); // disable ngnix webServer buffering
header("Content-Type: text/event-stream");
header("Cache-Control: no-cache");
ob_end_flush();  // close PHP output buffering
$inc=0;

while (
1) {
 
$result = "";
 
// wait for one Notify 10seconds instead of using sleep(10)
 
$result = $dbconn->pgsqlGetNotify(PDO::FETCH_ASSOC, 10000);

  if (
$result ) {
        echo
"id: $inc\ndata: ".stripslashes(json_encode($result))."\n\n";
       
$inc++;
  }

 
flush();
}
?>

Tested with HTML+JS sample file from Mozilla web site (ssedemo.php)
up
0
david at frankieandshadow dot com
3 years ago
It appears that pg_get_notify does not distinguish between no message waiting and a failure when checking - both seem to return FALSE.

I had to add a pg_check_connection(...) before pg_get_notify to check the connection is still alive (it's quite likely to be a long-standing connection with pg_get_notify as you'll be polling waiting for something to happen). In my case the remote database server had a hiccup, and without pg_check_connection the listeners failed to notice, so never saw later notifications.
To Top