1. Go to this page and download the library: Download ez-php/broadcast library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
ez-php / broadcast example snippets
use EzPhp\Broadcast\BroadcastServiceProvider;
$app->register(BroadcastServiceProvider::class);
use EzPhp\Broadcast\Broadcast;
Broadcast::to('notifications', 'UserCreated', ['id' => 42, 'name' => 'Alice']);
use EzPhp\Broadcast\BroadcastableInterface;
class UserCreated implements BroadcastableInterface
{
public function __construct(private readonly int $userId) {}
public function broadcastOn(): string
{
return 'notifications';
}
public function broadcastAs(): string
{
return 'UserCreated';
}
public function broadcastWith(): array
{
return ['id' => $this->userId];
}
}
Broadcast::event(new UserCreated(42));
use EzPhp\Broadcast\Broadcast;
use EzPhp\Broadcast\Broadcaster;
use EzPhp\Broadcast\Driver\ArrayDriver;
$driver = new ArrayDriver();
Broadcast::setBroadcaster(new Broadcaster($driver));
// ... exercise code under test ...
$events = $driver->eventsOn('notifications');
assert(count($events) === 1);
assert($events[0]['event'] === 'UserCreated');
Broadcast::resetBroadcaster();
use EzPhp\Http\Sse\SseEvent;
use EzPhp\Http\StreamedResponse;
public function events(Request $request): StreamedResponse
{
// Check authorisation here, before returning — headers are sent before the first event.
return StreamedResponse::sse(function (): \Generator {
foreach ($this->subscription() as $message) {
yield new SseEvent(json_encode($message, JSON_THROW_ON_ERROR), 'message');
}
});
}
use EzPhp\Broadcast\BroadcastDriverInterface;
final class RedisPubSubDriver implements BroadcastDriverInterface
{
public function __construct(private readonly \Redis $redis) {}
public function publish(string $channel, string $event, array $payload): void
{
$this->redis->publish($channel, json_encode([
'event' => $event,
'payload' => $payload,
]));
}
}
$app->bind(BroadcastDriverInterface::class, fn () => new RedisPubSubDriver($redis));
bash
composer
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.