PHP code example of flyokai / amp-channel-dispatcher

1. Go to this page and download the library: Download flyokai/amp-channel-dispatcher 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/ */

    

flyokai / amp-channel-dispatcher example snippets


use Amp\ByteStream\StreamChannel;
use Flyokai\AmpChannelDispatcher\{Dispatcher, RequestHandler, Request, Response};
use Flyokai\AmpChannelDispatcher\DefaultDispatcherChannel;
use Flyokai\AmpChannelDispatcher\Error\DefaultErrorHandler;
use function Flyokai\AmpChannelDispatcher\stackMiddleware;

final class PingHandler implements RequestHandler
{
    public function handleRequest(Request $request): Response
    {
        return new Response\SuccessResponse(requestId: $request->id());
    }
}

$channel = /* an Amp\Sync\Channel */;
$dispatcher = new Dispatcher(
    new DefaultDispatcherChannel($channel),
    stackMiddleware(new PingHandler() /*, $middleware1, $middleware2*/),
    new DefaultErrorHandler(),
);
$dispatcher->run();

$response = $dispatcher->sendRequest(new Request\Ping())->await();

$dispatcher->run();             // starts read & write loops via EventLoop::defer()
$future = $dispatcher->sendRequest(new MyRequest(...));   // returns null for MeekRequest
$response = $future->await();
$dispatcher->onStop(fn() => /* cleanup */);
$dispatcher->stop();            // graceful shutdown

final class LoggingMiddleware implements Middleware
{
    public function handleRequest(Request $request, RequestHandler $next): Response
    {
        // … pre …
        $response = $next->handleRequest($request);
        // … post …
        return $response;
    }
}

$pipeline = stackMiddleware($handler, $logging, $auth);
// composes: $logging → $auth → $handler

// Server side:
$context->addLocalIterator($iterator);

// Client side:
$remote = new RemoteIterator(/* … */);
foreach ($remote as $value) { /* … */ }