PHP code example of artisan-build / resonance

1. Go to this page and download the library: Download artisan-build/resonance 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/ */

    

artisan-build / resonance example snippets


// config/resonance.php
return [
    'default' => env('RESONANCE_CONNECTION', 'reverb'),

    'connections' => [
        'reverb' => [
            'broadcaster' => 'reverb',
            'key' => env('REVERB_APP_KEY'),
            'authToken' => env('RESONANCE_AUTH_TOKEN'),
            'host' => env('REVERB_HOST', '127.0.0.1'),
            'port' => env('REVERB_PORT', 8080),
            'forceTLS' => env('REVERB_SCHEME', 'https') === 'https',
            'channelAuthorization' => [
                'endpoint' => env('APP_URL').'/broadcasting/auth',
            ],
        ],

        'pusher' => [
            'broadcaster' => 'pusher',
            'key' => env('PUSHER_APP_KEY'),
            'authToken' => env('RESONANCE_AUTH_TOKEN'),
            'cluster' => env('PUSHER_APP_CLUSTER', 'mt1'),
            'forceTLS' => true,
            'channelAuthorization' => [
                'endpoint' => env('APP_URL').'/broadcasting/auth',
            ],
        ],

        'null' => [
            'broadcaster' => 'null',
        ],
    ],

    'namespace' => 'App.Events',
];

use ArtisanBuild\Resonance\Facades\Resonance;

// Using the default connection from config
$channel = Resonance::channel('orders');

$channel->listen('OrderShipped', function ($event) {
    echo "Order shipped: " . $event['order_id'];
});

use ArtisanBuild\Resonance\Facades\Resonance;

// Use a specific connection
Resonance::connection('reverb')->listen('orders', 'OrderShipped', function ($event) {
    // Handle internal events from your Reverb server
});

Resonance::connection('pusher')->listen('analytics', 'PageView', function ($event) {
    // Handle events from a third-party Pusher service
});

use ArtisanBuild\Resonance\Facades\Resonance;

Resonance::extend('ably', function ($app, $config) {
    return new AblyConnector($config);
});

use ArtisanBuild\Resonance\Resonance;

$resonance = new Resonance([
    'broadcaster' => 'reverb',
    'key' => 'your-app-key',
    'authToken' => 'your-sanctum-token',
    'host' => '127.0.0.1',
    'port' => 8080,
    'forceTLS' => false,
    'channelAuthorization' => [
        'endpoint' => 'https://your-app.com/broadcasting/auth',
    ],
]);

$resonance->listen('orders', 'OrderShipped', function ($event) {
    echo "Order shipped: " . $event['order_id'];
});

// Subscribe to a private channel
$channel = $resonance->private('orders.123');

$channel->listen('OrderUpdated', function ($event) {
    // Handle the event
});

// Join a presence channel
$presence = $resonance->join('chat.room.1');

$presence->here(function ($users) {
    // Users currently in the channel
});

$presence->joining(function ($user) {
    // A user joined
});

$presence->leaving(function ($user) {
    // A user left
});

$presence->listen('NewMessage', function ($event) {
    // Handle chat message
});

// Register a callback for when connection is established
$resonance->connected(function () {
    echo "Connected to WebSocket server!";
});

// Get the socket ID (useful for excluding sender)
$socketId = $resonance->socketId();

// Leave a specific channel
$resonance->leave('orders');

// Leave a single channel variant
$resonance->leaveChannel('private-orders.123');

// Disconnect entirely
$resonance->disconnect();

$channel = $resonance->encryptedPrivate('sensitive-data');

$channel->listen('SecretEvent', function ($event) {
    // Decrypted event data
});



namespace App\Console\Prompts;

use ArtisanBuild\Resonance\Facades\Resonance;
use ArtisanBuild\Resonance\Resonance as ResonanceInstance;
use Illuminate\Support\Collection;
use Laravel\Prompts\AsyncPrompt;
use Laravel\Prompts\Key;

class ChatPrompt extends AsyncPrompt
{
    protected ResonanceInstance $socket;
    protected mixed $channel;
    public Collection $messages;

    public function __construct()
    {
        $this->messages = collect([['system', 'Connecting...']]);

        $this->on('key', fn ($key) => match ($key) {
            Key::ENTER => $this->sendMessage($this->value()),
            Key::ESCAPE => $this->disconnect(),
            default => null,
        });

        $this->connect();
    }

    protected function connect(): void
    {
        // Use the facade - config provides auth token and endpoint
        $this->socket = Resonance::connection('reverb');

        $this->socket->connected(function () {
            $this->channel = $this->socket->private('chat');

            // Listen for all events on the channel
            $this->channel->listenToAll(function ($event, $data) {
                $this->handleEvent($event, $data);
            });

            // Or listen for specific events
            $this->channel->listen('MessageSent', function ($data) {
                $this->messages->push(['left', $data['message']]);
                $this->render();
            });

            // Listen for client whispers (peer-to-peer)
            $this->channel->listenForWhisper('typing', function ($data) {
                $this->typing = true;
                $this->render();
            });

            $this->messages = collect([['system', 'Connected! Start chatting...']]);
            $this->render();
        });
    }

    protected function sendMessage(string $message): void
    {
        if (empty($message)) return;

        // Send a whisper to other clients (no server round-trip)
        $this->channel->whisper('message', ['text' => $message]);

        $this->messages->push(['right', $message]);
        $this->typedValue = '';
        $this->render();
    }

    protected function disconnect(): void
    {
        $this->socket->disconnect();
        $this->submit();
    }
}
bash
php artisan vendor:publish --tag="resonance-config"