PHP code example of opekunov / laravel-centrifugo-broadcaster

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

    

opekunov / laravel-centrifugo-broadcaster example snippets


return [

    // .... //

    'providers' => [
        // Uncomment BroadcastServiceProvider
        App\Providers\BroadcastServiceProvider::class,
    ],

    // .... //

];

return [

        // .... //
    
        'centrifugo' => [
            'driver' => 'centrifugo',
            'secret'  => env('CENTRIFUGO_SECRET'),
            'apikey'  => env('CENTRIFUGO_APIKEY'),
            'api_path' => env('CENTRIFUGO_API_PATH', '/api'), // Centrifugo api endpoint (default '/api')
            'url'     => env('CENTRIFUGO_URL', 'http://localhost:8000'), // centrifugo api url
            'verify'  => env('CENTRIFUGO_VERIFY', false), // Verify host ssl if centrifugo uses this
            'ssl_key' => env('CENTRIFUGO_SSL_KEY', null), // Self-Signed SSl Key for Host (,
        
       // .... //
       
];

// routes/channels.php

// In Centrifugo 5+, channel namespaces are separated by ':'. The '$' prefix is not used.
Broadcast::channel('namespace:channel', function (){
    // Some auth logic for example:
    return \Auth::user()->group === 'private-channel-group';
});

Broadcast::channel('namespace:channel-{id}', function ($user, $id){
    return $user->id === $id;
});


// App/Events/SendMessageEvent.php

namespace App\Events;

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

//Use "implements ShouldBroadcast" if you want add event to queue
class SendMessageEvent implements ShouldBroadcastNow
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    /**
     * @var string Message text
     */
    private $messageText;

    public function __construct(string $messageText)
    {
        $this->messageText = $messageText;
    }

    /**
     * The event's broadcast name.
     *
     * @return string
     */
    public function broadcastAs()
    {
        //example event broadcast name. Show in Web Socket JSON
        return 'message.new';
    }


    /**
     * Get the data to broadcast.
     *
     * @return array
     */
    public function broadcastWith()
    {
        return ['message' => $this->messageText];
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new Channel('public:chat');
        // or return new PrivateChannel('private:chat');
    }
}



declare(strict_types = 1);

namespace App\Http\Controllers;

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

class ExampleController
{

    public function example(Centrifugo $centrifugo)
    {
        //or $centrifugo = new Centrifugo();
        //or centrifugo()

        // Send message into channel
        $centrifugo->publish('news', ['message' => 'Hello world']);

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

        // Generate subscription token
        $expire = now()->addDay(); //or you can use Unix: $expire = time() + 60 * 60 * 24;
        $token = $centrifugo->generateSubscriptionToken((string)Auth::id(), 'channel', $expire, [
            'name' => Auth::user()->name,
        ]);

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

        //Get channel presence information (all clients currently subscribed on this channel).
        $centrifugo->presence('news');

    }
}

// Get the last 10 messages from the channel
$history = $centrifugo->history('chat:room1', limit: 10);

// Get messages in reverse order (newest first)
$history = $centrifugo->history('chat:room1', limit: 10, reverse: true);

// Pagination: get messages from a specific position
$history = $centrifugo->history('chat:room1', limit: 50, offset: 100, epoch: 'EPOCH');

// Remove channel history
$centrifugo->historyRemove('chat:room1');

// Get full presence info (all clients with their data)
$presence = $centrifugo->presence('chat:room1');

// Get short presence stats (number of clients and unique users)
$stats = $centrifugo->presenceStats('chat:room1');

// Subscribe a user to a channel from the server side
$centrifugo->subscribe('notifications:user1', 'user1');

// With additional info and data
$centrifugo->subscribe('notifications:user1', 'user1',
    info: ['role' => 'admin'],
    data: ['message' => 'Welcome!']
);

// Unsubscribe a user from a channel
$centrifugo->unsubscribe('notifications:user1', 'user1');

// Disconnect a user entirely
$centrifugo->disconnect('user1');
bash
php artisan install:broadcasting