PHP code example of mbolli / php-via

1. Go to this page and download the library: Download mbolli/php-via 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/ */

    

mbolli / php-via example snippets



Mbolli\PhpVia\Via;
use Mbolli\PhpVia\Config;
use Mbolli\PhpVia\Context;

$config = new Config();
$config->withTemplateDir(__DIR__ . '/templates');
$app = new Via($config);

$app->page('/', function (Context $c): void {
    $count = $c->signal(0, 'count');
    $step  = $c->signal(1, 'step');

    $c->action(function () use ($count, $step, $c): void {
        $count->setValue($count->int() + $step->int());
        $c->syncSignals();
    }, 'increment');

    $c->view('counter.html.twig');
});

$app->start();

$name = $c->signal('Alice', 'name');
$name->string();          // read
$name->setValue('Bob');    // write → auto-pushes to browser

$save = $c->action(function () use ($c): void {
    $c->sync();
}, 'save');

$c->view('dashboard.html.twig', ['user' => $user]);

$app->page('/blog/{year}/{slug}', function (Context $c, string $year, string $slug): void {
    // ...
});

$a = $c->component($counterWidget, 'a');
$b = $c->component($counterWidget, 'b');

$c->onDisconnect(fn() => /* cleanup */);
$c->setInterval(fn() => $c->sync(), 2000);  // auto-cleaned on disconnect
$app->onClientConnect(fn(string $id) => /* ... */);
$app->setInterval(fn() => $app->broadcast(Scope::GLOBAL), 5000); // process-wide timer

$app->group('/admin', function (Via $app): void {
    $app->page('/', fn(Context $c) => ...);      // → /admin
    $app->page('/users', fn(Context $c) => ...); // → /admin/users
})->middleware(new AuthMiddleware());

$c->broadcast();                    // same scope
$app->broadcast(Scope::GLOBAL);     // all contexts
$app->broadcast('room:lobby');      // custom scope

use Mbolli\PhpVia\Broker\RedisBroker;
use Mbolli\PhpVia\Broker\NatsBroker;

// Redis ($config->withBroker(new RedisBroker(
    host: 'redis.internal',
    password: $_ENV['REDIS_PASSWORD'],
    tls: true,
));

// NATS (raw OpenSwoole socket — no extra extension)
$config->withBroker(new NatsBroker('127.0.0.1', 4222));

// NATS with token auth and TLS
$config->withBroker(new NatsBroker(
    host: 'nats.internal',
    authToken: $_ENV['NATS_TOKEN'],
    tls: true,
));

// Error observability — called on every connection drop
$config->onBrokerError(fn(\Throwable $e) => error_log('Broker: ' . $e->getMessage()));

composer 

php app.php
# → http://localhost:3000