PHP code example of hosmelq / sse-saloon

1. Go to this page and download the library: Download hosmelq/sse-saloon 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/ */

    

hosmelq / sse-saloon example snippets


use HosmelQ\SSE\Saloon\Traits\HasServerSentEvents;
use Saloon\Http\Request;
use Saloon\Enums\Method;

class StreamNotifications extends Request
{
    use HasServerSentEvents;

    protected Method $method = Method::GET;

    public function resolveEndpoint(): string
    {
        return '/notifications/stream';
    }
}

$response = $connector->send(new StreamNotifications());

foreach ($response->asEventSource()->events() as $event) {
    echo "Data: {$event->data}\n";
    echo "Event: {$event->event}\n";
    echo "ID: {$event->id}\n";
}

use HosmelQ\SSE\Saloon\Traits\HasServerSentEvents;
use Saloon\Http\Request;
use Saloon\Enums\Method;

class CustomizedStream extends Request
{
    use HasServerSentEvents {
        defaultConfig as defaultSSEConfig;
        defaultHeaders as defaultSSEHeaders;
    }

    protected Method $method = Method::GET;

    public function __construct(private int $readTimeout, private string $token) {}

    public function resolveEndpoint(): string
    {
        return '/api/stream';
    }

    protected function defaultConfig(): array
    {
        return array_merge($this->defaultSSEConfig(), [
            'read_timeout' => $this->readTimeout,
        ]);
    }

    protected function defaultHeaders(): array
    {
        return array_merge($this->defaultSSEHeaders(), [
            'Authorization' => 'Bearer ' . $this->token,
        ]);
    }
}

use HosmelQ\SSE\SSEProtocolException;

try {
    $response = $connector->send(new EventStreamRequest());
    
    foreach ($response->asEventSource()->events() as $event) {
    }
} catch (SSEProtocolException $e) {
    echo 'SSE Error: ' . $e->getMessage();
}