Pdo\Pgsql::getNotify

(PHP 8 >= 8.4.0)

Pdo\Pgsql::getNotify — Renvoie une notification asynchrone

Description

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

Renvoie un jeu de résultats représentant une notification asynchrone en attente.

Liste de paramĂštres

fetchMode

Le format sous lequel le jeu de rĂ©sultats doit ĂȘtre, une des constantes suivantes:

timeoutMilliseconds
Le temps d'attente pour une réponse, en millisecondes.

Valeurs de retour

Si une notification est en attente, retourne une seule ligne, sinon retourne false. La ligne possÚde un champ message (le nom du canal) et un champ pid (l'identifiant du processus du backend émetteur). Si la notification transporte une charge utile non vide, la ligne possÚde également un champ payload. Avec PDO::FETCH_NUM, ces champs se trouvent aux indices 0, 1 et 2.

Erreurs / Exceptions

Une ValueError est lancée si fetchMode n'est pas une des constantes PDO::FETCH_* valides.

Une ValueError est lancée si timeoutMilliseconds est inférieur à 0.

Une Warning est lancĂ©e si timeoutMilliseconds est supĂ©rieur Ă  la valeur qui peut ĂȘtre contenue dans un entier signĂ© 32 bits, auquel cas ce sera la valeur maximale d'un entier signĂ© 32 bits.

Exemples

Exemple #1 Exemple avec Pdo\Pgsql::getNotify()

S'abonner à un canal avec LISTEN, puis lire la prochaine notification en attente avec un délai d'attente d'une seconde.

<?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);
?>

Résultat de l'exemple ci-dessus est similaire à :

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

Voir aussi

add a note

User Contributed Notes 1 note

up
0
sage at sage dot sk ¶
5 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.