PHP code example of phasync / swerve

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


 // swerve.php

return new Swerve\RequestHandler(function (Swerve\ClientRequest $request) {
    $request->sendResponseHeaders(200, ['content-type' => 'text/plain']);
    $request->write("Hello, World\n");
});

    // swerve.php

   return new Swerve\RequestHandler(function (Swerve\ClientRequest $request) {
       $request->sendResponseHeaders(200, ['content-type' => 'text/plain']);
       $request->write("Hello, World\n");
   });
   

    // swerve.php

   use phasync;
   use phasync\IOException;

   return new Swerve\RequestHandler(function (Swerve\ClientRequest $request) {
       $request->sendResponseHeaders(200, ['content-type' => 'text/event-stream', 'cache-control' => 'no-cache']);
       $request->flush(); // the head goes out now, not with the first event
       try {
           for ($n = 1; ; ++$n) {
               $request->write("data: $n\n\n");
               phasync::sleep(1);
           }
       } catch (IOException) {
           // the client left
       }
   });
   



function entry(string $appDir, ?string $docroot = null, ?string $file = null): Swerve\RequestHandler

use Swerve\Swerve;

Swerve::ini(['memory_limit' => '512M']);  // php.ini settings, applied by swerve's startup restart
Swerve::onWorkerStart(function () {           // in every worker, before the application loads
    // set up what the worker shares between requests; coroutines started here run for its life
});

$locales = new WeakMap();   // per Scope
phasync::onScopeChange(function (Scope $new, ?Scope $old) use ($locales) {
    if (null !== $old) {
        $locales[$old] = setlocale(LC_ALL, 0);
    }
    setlocale(LC_ALL, $locales[$new] ?? 'C');
});

Swerve::log()->warning('Payment {id} declined', ['id' => $id]);

use Swerve\Swerve;

Swerve::publish('chat', $message);

foreach (Swerve::subscribe('chat') as $message) {
    // every message published to 'chat' from the moment subscribe() returned
}

$cache = Swerve::cache();
$user  = $cache->get("user.$id") ?? load_user($id);
$cache->set("user.$id", $user, 60);

function nightlyReport(): void
{
    if ($claim = Swerve::claim('nightly-report')->acquire()) {
        work();
    }
}   // $claim goes out of scope: released
json
{"autoload": {"files": ["integrate-with-swerve.php"]}}