PHP code example of le0m / yii2-broadcasting

1. Go to this page and download the library: Download le0m/yii2-broadcasting 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/ */

    

le0m / yii2-broadcasting example snippets


'modules' => [
    // configure a redis connection
    'redis' => [
        'class' => 'yii\redis\Connection',
        'hostname' => 'localhost',
        'port' => 6379,
        'database' => 0,
    ],
    'broadcasting' => [
        'class' => 'le0m\broadcasting\BroadcastManager',
        'broadcaster' => [
            'class' => 'le0m\broadcasting\broadcasters\RedisBroadcaster',
            // use the redis connection component (default) or define a new one
            'redis' => 'redis',
            'channels' => [
                // authorization callback for private and presence channels
                'comments.{postId}' => function (yii\web\User $user, $postId) {
                    // use basic roles or RBAC
                    return $user->can('doSomething', ['post' => $postId]);
                },
            ],
        ],
    ]
]

class NotificationController extends Controller
{
    // ...
    
    public function behaviors()
    {
        return [
            // ...
            'authenticator' => [
                // define your authenticator behavior
                'class' => HttpBearerAuth::class,
            ]
        ];
    }
    
    public function actions()
    {
        return [
            'auth' => [
                'class' => 'le0m\broadcasting\actions\AuthAction'
            ]
        ];
    }
    
    // ...
}

namespace common\models;

use le0m\broadcasting\channels\PrivateChannel;
use le0m\broadcasting\BroadcastEvent;

class MessageEvent extends BroadcastEvent
{
    public $text;
    public $author;
    public $time;
    
    private $_postId;


    public function broadcastOn()
    {
        return new PrivateChannel('comments.' . $this->getPostId());
    }

    public function broadcastAs()
    {
        return 'new';
    }
    
    public function getPostId()
    {
        return $this->_postId;
    }
    
    public function setPostId($postId) {
        $this->_postId = $postId;
    }
}

$event = new MessageEvent([
    'text' => $text,
    'author' => $user->username,
    'time' => time()
]);
$event->toOthers()->broadcast();

php composer.phar