Created
March 24, 2021 13:01
-
-
Save carbontwelve/4f30cd200be8e51c2bf82cdef00d530a to your computer and use it in GitHub Desktop.
Example of using Ably's Batch mode with Laravel
This file contains hidden or 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 | |
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); | |
} | |
} |
This file contains hidden or 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 | |
/* | |
* 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() | |
]); |
This file contains hidden or 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 | |
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