Skip to content

Instantly share code, notes, and snippets.

@carbontwelve
Created March 24, 2021 13:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carbontwelve/4f30cd200be8e51c2bf82cdef00d530a to your computer and use it in GitHub Desktop.
Save carbontwelve/4f30cd200be8e51c2bf82cdef00d530a to your computer and use it in GitHub Desktop.
Example of using Ably's Batch mode with Laravel
<?php
namespace App\Broadcasting;
use Illuminate\Broadcasting\Broadcasters\AblyBroadcaster;
class AblyBatchBroadcaster extends AblyBroadcaster
{
private $batch = [];
public function broadcast(array $channels, $event, array $payload = [])
{
foreach ($this->formatChannels($channels) as $channel) {
if (!isset($this->batch[$channel])) {
$this->batch[$channel] = [];
}
$this->batch[$channel][] = [
'name' => $event,
'data' => $payload
];
}
}
public function handle()
{
$batch = [];
foreach ($this->batch as $channel => $messages)
{
array_push($batch, [
'channels' => $channel,
'messages' => $messages,
]);
}
$json = json_encode($batch);
$this->batch = [];
return $this->ably->post('/messages', [], $json);
}
}
<?php
/*
* Example Usage, as opposed to firing broadcast() on each of these
* our method sends them all as one API request to Ably.
*/
batchBroadcast([
new ShouldBroadcastImplementationA(),
new ShouldBroadcastImplementationB(),
new ShouldBroadcastImplementationC()
]);
<?php
if (!function_exists('batchBroadcast')) {
function batchBroadcast(array $events) {
$batchBroadcaster = new \App\Broadcasting\AblyBatchBroadcaster(
new Ably\AblyRest(env('ABLY_KEY'))
);
foreach ($events as $event) {
$event = new \Illuminate\Broadcasting\BroadcastEvent($event);
$event->handle($batchBroadcaster);
}
return $batchBroadcaster->handle();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment