PHP code example of prsw / amphp-bundle

1. Go to this page and download the library: Download prsw/amphp-bundle 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/ */

    

prsw / amphp-bundle example snippets


return [
    PRSW\AmphpBundle\AmphpBundle::class => ['all' => true],
];

use Amp\Websocket\Server\WebsocketClientHandler;
use Amp\Websocket\Server\WebsocketClientGateway;
use Amp\Websocket\WebsocketClient;
use PRSW\AmphpBundle\Websocket\Attribute\WebsocketEndpoint;

#[WebsocketEndpoint(path: '/chat')]
class ChatHandler implements WebsocketClientHandler
{
    public function handleClient(
        WebsocketClient $client,
        \Amp\Http\Server\Request $request,
        \Amp\Http\Server\Response $response,
    ): void {
        $gateway = new WebsocketClientGateway();
        $gateway->addClient($client);
        $gateway->broadcastText('User joined');

        foreach ($client as $message) {
            $gateway->broadcastText($message->buffer());
        }
    }
}

use PRSW\AmphpBundle\Runtime\Bridge\PriorityResetInterface;
use Symfony\Contracts\Service\ResetInterface;

final class MyConnectionResetter implements PriorityResetInterface
{
    public function __construct(
        private readonly MyConnectionPool $pool,
    ) {}

    public function reset(): void
    {
        $this->pool->releaseConnections();
    }

    public function getPriority(): int
    {
        return 50;
    }
}

use PRSW\AmphpBundle\Bridge\Symfony\HttpFoundation\SseEvent;
use PRSW\AmphpBundle\Bridge\Symfony\HttpFoundation\SseResponse;

#[Route('/events')]
public function stream(): SseResponse
{
    return new SseResponse(function () {
        while (true) {
            yield new SseEvent(data: ['time' => time()], event: 'tick');
            \Amp\delay(1);
        }
    });
}

#[Route('/stream')]
public function stream(): StreamedResponse
{
    return new StreamedResponse(function () {
        $handle = yield \Amp\File\open('/path/to/file', 'r');
        while (null !== $chunk = yield $handle->read()) {
            yield $chunk;
        }
    });
}

use PRSW\AmphpBundle\Metrics\Metric;
use PRSW\AmphpBundle\Metrics\MetricCollectorInterface;

final class OrderMetrics implements MetricCollectorInterface
{
    public function collect(): array
    {
        return [
            new Metric('orders_total', 42.0, 'Total orders', 'counter', ['status' => 'completed']),
        ];
    }
}