PHP 8.6.0 Alpha 2 available for testing

Pdo\Pgsql::getNotify

(PHP 8 >= 8.4.0)

Pdo\Pgsql::getNotify非同期に通知を取得する

説明

public function Pdo\Pgsql::getNotify(int $fetchMode = PDO::FETCH_DEFAULT, int $timeoutMilliseconds = 0): array|false

保留中の非同期な通知を示す結果セットを返します。

パラメータ

fetchMode

結果セットを返すフォーマット。 次のいずれかの定数:

timeoutMilliseconds
レスポンスを待つ時間の長さ。ミリ秒で指定します。

戻り値

通知が保留中だった場合は1行を返し、そうでなければ false を返します。 この行には、message フィールド(チャネル名)と pid フィールド(通知を送信したバックエンドのプロセス ID)が含まれます。 通知が空でないペイロードを伴う場合は、この行に payload フィールドも含まれます。 PDO::FETCH_NUM の場合、これらのフィールドは インデックス 012 にあります。

エラー / 例外

fetchMode が有効な PDO::FETCH_* 定数のいずれでもない場合、ValueError がスローされます。

timeoutMilliseconds0 未満の場合、 ValueError がスローされます。

timeoutMilliseconds が符号付き32ビットの整数に 収まらない場合、E_WARNING が発生し、 その値は符号付き32ビットの整数の最大値に丸められます。

例1 Pdo\Pgsql::getNotify() の例

LISTEN でチャネルを購読し、1秒のタイムアウトで 次の保留中の通知を読み取ります。

<?php
$db = new Pdo\Pgsql('pgsql:dbname=test host=localhost', $user, $pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$db->exec('LISTEN messages');
$db->exec("NOTIFY messages, 'hello'");

$notification = $db->getNotify(PDO::FETCH_ASSOC, 1000);
var_export($notification);
?>

上の例の出力は、 たとえば以下のようになります。

array (
  'message' => 'messages',
  'pid' => 1928,
  'payload' => 'hello',
)

参考

add a note

User Contributed Notes 1 note

up
0
sage at sage dot sk
6 months ago
This page needs an example to understand that you **need** to explicitly call LISTEN before using getNotify, like shown in https://www.php.net/manual/en/function.pg-get-notify.php

<?php

$db = new PDO($dsn, $user, $password, $options);
$db->query('LISTEN test');
$notification = $db->pgsqlGetNotify(PDO::FETCH_ASSOC, 10000);

// or

$db = new Pdo\Pgsql($dsn, $user, $password, $options);
$db->query('LISTEN test');
$notification = $db->getNotify(PDO::FETCH_ASSOC, 10000);

// now you can call NOTIFY elsewhere
// PG> NOTIFY test, 'payload string';
var_dump($notification);

?>

array(3) {
  ["message"]=>
  string(4) "test"
  ["pid"]=>
  int(123565)
  ["payload"]=>
  string(14) "payload string"
}

If you called NOTIFY before calling LISTEN, nothing will be returned!

You receive the first notification only, and you have to call getNotify again. And call LISTEN again if DB connection drops.
To Top