Created
March 11, 2015 12:49
-
-
Save chernomyrdin/96812377f1ac5bf567b8 to your computer and use it in GitHub Desktop.
Using LISTEN/NOTIFY PostgreSQL in PHP (async/pool mode)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Class Main - Проверяем возможность работы с LISTEN/NOTIFY в PostgreSQL | |
* Вывод: Подобное возможно только начиная с PHP 5.6, так как только там появилась функция pg_socket($dbh) | |
* Так-же демонстрируется возможность работать по опросу, что менее удобно, но это лучше чем ничего | |
*/ | |
class Main { | |
/** | |
* Database connect string | |
* @type string | |
*/ | |
const DataSource = 'user=user dbname=user'; | |
/** | |
* Timeout for sleep | |
* @type int | |
*/ | |
const PoolTimeout = 5; | |
/** | |
* Timeout for select | |
* @type int | |
*/ | |
const SelectTimeout = 60; | |
/** | |
* Database handle | |
* @var resource | |
*/ | |
private $dbh; | |
/** | |
* @__construct | |
* @throws Exception | |
*/ | |
public function __construct () { | |
$this->dbh = pg_connect(static::DataSource); | |
if ($this->dbh === FALSE) { | |
throw new Exception ('pg_connect() error'); | |
} | |
if (pg_query($this->dbh, "LISTEN test") === FALSE) { | |
throw new Exception ( | |
'error send LISTEN command: ' . pg_last_error($this->dbh) | |
); | |
} | |
while (TRUE) { | |
$num = (function_exists('pg_socket') | |
? stream_select( | |
$read = array(pg_socket($this->dbh)), | |
$null = NULL, | |
$null = NULL, | |
static::SelectTimeout | |
) | |
: ((sleep(static::PoolTimeout) === FALSE) | |
? FALSE | |
: 1 | |
) | |
); | |
if ($num === FALSE) { | |
throw new Exception('Error in get ready'); | |
} | |
if (pg_connection_status($this->dbh) !== PGSQL_CONNECTION_OK) { | |
throw new Exception('pg_connection_status() is not PGSQL_CONNECTION_OK'); | |
} | |
elseif ($num) { | |
$notify = pg_get_notify($this->dbh); | |
if ($notify !== FALSE) { | |
$this->notify($notify); | |
} | |
# else { | |
# echo "Nothing to listen\n"; | |
# } | |
} | |
} | |
} | |
/** | |
* Process notify message | |
* @param array $notify | |
*/ | |
public function notify ($notify) { | |
var_dump($notify); | |
} | |
} | |
# function main ($argc, $argv) { | |
try { | |
new Main; | |
} | |
catch (Exception $e) { | |
echo "$e\n"; | |
} | |
# } | |
# [EOF] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment