Channels and messaging
Examples
Every example of this topic, with its output.
phasync::channel#
phasync::run(function () {
phasync::channel($reader, $writer, 10); // a buffer of 10 values
phasync::go(function () use ($writer) {
foreach (['a.txt', 'b.txt', 'c.txt'] as $file) {
$writer->write($file);
}
$writer->close();
});
foreach ($reader as $file) { // ends when the writer closes
echo "processing $file\n";
}
});phasync::publisher#
phasync::run(function () {
phasync::publisher($subscribers, $publisher);
foreach ([1, 2] as $i) {
$subscription = $subscribers->subscribe();
phasync::go(function () use ($subscription, $i) {
foreach ($subscription as $event) {
echo "subscriber $i got $event\n";
}
});
}
$publisher->write('deployed');
$publisher->close();
});ChannelException#
phasync::run(function () {
phasync::channel($read, $write, 1);
phasync::go(fn () => $read->close());
phasync::sleep(0.01);
try {
$write->write('late');
} catch (phasync\ChannelException $e) {
echo $e->getMessage(), "\n"; // Channel is closed
}
});ReadChannelInterface#
phasync::run(function () {
phasync::channel($read, $write);
phasync::go(function () use ($write) {
$write->write('hello');
$write->close();
});
foreach ($read as $message) {
echo $message, "\n"; // hello
}
});ReadChannelInterface::read#
phasync::run(function () {
phasync::channel($read, $write, 2);
$write->write(null);
$write->close();
$read->read(eof: $eof); // null, $eof is false: a value
$read->read(eof: $eof); // null, $eof is true: the end
});SubscriberInterface#
phasync::run(function () {
phasync::publisher($subscribers, $publisher);
$subscription = $subscribers->subscribe();
phasync::go(function () use ($publisher) {
$publisher->write('a');
$publisher->write('b');
$publisher->close();
});
foreach ($subscription as $message) {
echo $message, "\n"; // a, then b
}
});SubscribersInterface#
phasync::run(function () {
phasync::publisher($subscribers, $publisher);
$subscription = $subscribers->subscribe();
$publisher->write('first');
$publisher->close();
echo $subscription->read(); // first
});SubscribersInterface::subscribe#
phasync::run(function () {
phasync::publisher($subscribers, $publisher);
$subscription = $subscribers->subscribe();
phasync::go(function () use ($subscription) {
foreach ($subscription as $event) {
echo "got $event\n";
}
});
$publisher->write('deployed');
$publisher->close();
});Queue#
$queue = new phasync\Util\Queue();
$queue->enqueue('a');
$queue->enqueue('b');
$queue->tryDequeue($value); // $value is 'a'
echo count($queue), "\n"; // 1QueueInterface#
$queue = new phasync\Util\Queue();
$queue->enqueue('job');
if ($queue->tryDequeue($job)) {
echo $job; // job
}WriteChannelInterface#
phasync::run(function () {
phasync::channel($read, $write, 3);
phasync::go(function () use ($write) {
foreach ([1, 2, 3] as $number) {
$write->write($number);
}
$write->close();
});
foreach ($read as $number) {
echo $number, "\n";
}
});