PHP code example of macula-io / macula-php

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

    

macula-io / macula-php example snippets


use Macula\NodeKey;
use Macula\Notice;
use Macula\Pool;
use Macula\Seed;
use Macula\StreamData;
use Macula\StreamEnd;
use Macula\StreamMode;

$key = NodeKey::loadOrCreate('node.key');
$pool = Pool::connect($key, [new Seed('station-fi-helsinki.macula.io', 4433, $stationId)],
    realmTrust: [$realm => $realmKeyHex]);

// A call reaches a provider by direct dial: its advertisement from the DHT,
// trusted only when the realm key authorizes it, and its station dialed.
$answer = $pool->call($realm, 'mcl-echo/echo', 'hello');

// Publish and subscribe; topics name a kind of fact, ids go in the payload.
// A subscription hands back an Event, or a Notice when its events may have
// been missed: its link to the station ended, or a gap followed.
$sub = $pool->subscribe($realm, 'acme/demo/greeting_sent_v1');
$pool->publish($realm, 'acme/demo/greeting_sent_v1', ['text' => 'hi']);
foreach ($sub->events(idleMs: 2_000) as $item) {
    if ($item instanceof Notice) {
        echo "may have missed events: {$item->kind} ({$item->reason})\n";
        continue;
    }
    echo json_encode($item->payload), "\n";
}

// Streams: a server stream's chunks arrive until its end.
$stream = $pool->openStream($realm, 'mcl-tube/watch', StreamMode::Server);
foreach ($stream as $event) {
    if ($event instanceof StreamEnd) {
        break;
    }
}
$stream->free();

$pool->close();

$served = $pool->serve($realm, $pool->ownProcedure('ring'), Macula\ServePolicy::open());   // ~<node_id>/ring: no org, no realm key
while (true) {
    $served->handle(fn (Macula\Request $r) => ['answered' => $r->caller], timeoutMs: 1_000);
}

use Macula\Group;
use Macula\GroupError;

$group = new Group("{$realmName}/{$org}/chat", ucan: $grantFromTheOrg);
$sub = $pool->subscribeGroup($realm, "{$group->prefix}/said_v1", $group);
$pool->publishGroup($realm, "{$group->prefix}/said_v1", ['text' => 'hi'], $group);