PHP code example of phasync / swerve-spiral

1. Go to this page and download the library: Download phasync/swerve-spiral 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/ */

    

phasync / swerve-spiral example snippets


 // swerve.php, next to composer.json

return Swerve\Psr15\Bridge::wrap(new Swerve\Spiral\Handler(__DIR__, kernel: App\MyKernel::class));

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Spiral\Router\Annotation\Route;
use Swerve\Psr15\WebSocketResponse;
use Swerve\WebSocket;

final class EchoController
{
    #[Route(route: '/echo', name: 'echo', methods: ['GET'])]
    public function echo(ServerRequestInterface $request): ResponseInterface
    {
        return WebSocketResponse::from($request, static function (WebSocket $ws) {
            foreach ($ws as $message) {                 // ends when the connection closes
                $ws->isBinary() ? $ws->sendBinary($message) : $ws->send("echo: $message");
            }
        });
    }
}

use Swerve\Swerve;

#[Route(route: '/news', name: 'news', methods: ['GET'])]
public function news(ServerRequestInterface $request): ResponseInterface
{
    return WebSocketResponse::from($request, static function (WebSocket $ws) {
        foreach (Swerve::subscribe('news') as $message) {
            $ws->send($message);
        }
    });
}

#[Route(route: '/news', name: 'news-post', methods: ['POST'])]
public function post(InputManager $input): string
{
    Swerve::publish('news', (string) $input->data('text'));

    return 'sent';
}

#[Route(route: '/chat', name: 'chat', methods: ['GET'])]
public function chat(ServerRequestInterface $request, AuthContextInterface $auth, SessionScope $session): ResponseInterface
{
    $user = $auth->getActor() ?? throw new ForbiddenException();
    $room = $session->getSection('chat')->get('room', 'lobby');

    return WebSocketResponse::from($request, static function (WebSocket $ws) use ($user, $room) {
        // $user and $room, not $auth or $session
    });
}