变更数据捕获
Change Data Capture (CDC) is a technique for observing every INSERT, UPDATE, and DELETE that occurs on a database table, in real time, without polling. PyroSQL exposes a streaming SUBSCRIBE TO CHANGES ON <table> SQL command that yields rows as DML operations are committed to the WAL (Write-Ahead Log). Weaver ORM wraps this mechanism in CdcSubscriber and hydrates each row into a typed CdcEvent.
Common use cases:
- Audit logs — record every change to sensitive tables without modifying application code.
- Cache invalidation — invalidate Redis or Memcached keys the moment a row changes.
- Real-time sync — propagate changes to downstream systems such as Elasticsearch or a message queue.
- Event sourcing — treat the WAL as an ordered event stream.
CdcSubscriber
use Weaver\ORM\PyroSQL\Cdc\CdcSubscriber;
use Weaver\ORM\PyroSQL\PyroSqlDriver;
$driver = new PyroSqlDriver($connection);
$subscriber = new CdcSubscriber($connection, $driver);
subscribe(string $table, ?string $from = 'latest'): Generator
Subscribe to changes on a single table. Returns a Generator that yields CdcEvent objects as DML operations are committed. The generator is long-running; use break to stop consuming events.
$from = 'latest'— receive only events that occur after the subscription is opened.$from = '12345678'— replay events from WAL LSN12345678onwards.$from = null— use the server default start position.
foreach ($subscriber->subscribe('orders') as $event) {
// handle event
if ($event->isInsert()) {
echo 'New order: ' . $event->after['id'] . "\n";
}
}
Executes:
SUBSCRIBE TO CHANGES ON "orders" FROM latest