PHP code example of denis660 / laravel-centrifugo

1. Go to this page and download the library: Download denis660/laravel-centrifugo 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/ */

    

denis660 / laravel-centrifugo example snippets




namespace App\Events;

use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class OrderShipmentStatusUpdated implements ShouldBroadcast
{
    use Dispatchable;
    use SerializesModels;

    public function __construct(
        public int $orderId,
        public string $status,
    ) {
    }

    public function broadcastOn(): array
    {
        return [new PrivateChannel("orders.{$this->orderId}")];
    }

    public function broadcastAs(): string
    {
        return 'shipment.status.updated';
    }

    public function broadcastWith(): array
    {
        return [
            'order_id' => $this->orderId,
            'status' => $this->status,
        ];
    }
}



use Illuminate\Support\Facades\Broadcast;

Broadcast::channel('orders.{orderId}', function ($user, int $orderId) {
    return (int) $user->id === (int) $orderId; // Replace with your own access rule.
});

OrderShipmentStatusUpdated::dispatch($order->id, 'packed');



use denis660\Centrifugo\Centrifugo;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::middleware('auth')->get('/centrifugo/connection-token', function (Request $request, Centrifugo $centrifugo) {
    return [
        'token' => $centrifugo->generateConnectionToken(
            (string) $request->user()->getAuthIdentifier(),
            300,
        ),
    ];
});


declare(strict_types = 1);

namespace App\Http\Controllers;

use denis660\Centrifugo\Centrifugo;
use Illuminate\Support\Facades\Auth;

class ExampleController
{
    public function example(Centrifugo $centrifugo)
    {
        // Send a message to the news channel
        $centrifugo->publish('news', ['message' => 'Hello world']);

        // Generate a connection token
        $token = $centrifugo->generateConnectionToken((string)Auth::id(), 0, [
            'name' => Auth::user()->name,
        ]);

        // Generate a token for a private channel connection with a 5 minute TTL
        $privateToken = $centrifugo->generatePrivateChannelToken((string)Auth::id(), 'channel', 5 * 60, [
            'name' => Auth::user()->name,
        ]);

        // Get a list of active channels
        $centrifugo->channels();

        // Get information about the news channel and its active clients
        $centrifugo->presence('news');
    }
}
bash
php artisan centrifuge:install