PHP code example of godjarvis / hyperf-sse

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

    

godjarvis / hyperf-sse example snippets


GodJarvis\HyperfSse\Contract\SseDriverInterface
    => GodJarvis\HyperfSse\Driver\SseDriverFactory

use GodJarvis\HyperfSse\SseEmitter;
use GodJarvis\HyperfSse\SseService;
use Hyperf\Context\RequestContext;

public function connect(SseService $sse, SseEmitter $emitter): void
{
    // 必须从服务端认证上下文获取,不要直接使用 query 中的 user_id。
    $subject = (string) $this->request->getAttribute('authenticated_user_id');
    $lastEventId = RequestContext::get()?->getHeaderLine('Last-Event-ID') ?: null;

    $emitter->emit($sse->subscribe($subject, $lastEventId));
}

$sse->notify(
    subject: $userId,
    event: 'task_completed',
    data: [
        'task_id' => $taskId,
        'status' => 'completed',
        'result_url' => $resultUrl,
    ],
);

$sse->broadcast('maintenance', [
    'message' => '系统将在 10 分钟后维护',
]);

use GodJarvis\HyperfSse\Contract\SseDriverInterface;

final class CustomSseDriver implements SseDriverInterface
{
    // subscribe / notify / broadcast
}

'driver' => 'custom',
'drivers' => [
    'custom' => CustomSseDriver::class,
],

yield SseMessage::heartbeat();
bash
php bin/hyperf.php vendor:publish godjarvis/hyperf-sse
text
config/autoload/sse.php