PHPackages                             le0m/yii2-broadcasting - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [HTTP &amp; Networking](/categories/http)
4. /
5. le0m/yii2-broadcasting

ActiveYii2-extension[HTTP &amp; Networking](/categories/http)

le0m/yii2-broadcasting
======================

Websocket message broadcasting module

1.0.0(6y ago)31.0kMITPHP

Since Jul 12Pushed 6y agoCompare

[ Source](https://github.com/le0m/yii2-broadcasting)[ Packagist](https://packagist.org/packages/le0m/yii2-broadcasting)[ RSS](/packages/le0m-yii2-broadcasting/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (2)Versions (4)Used By (0)

Yii2-broadcasting
=================

[](#yii2-broadcasting)

[![Latest Stable Version](https://camo.githubusercontent.com/ea39366d11edc3a724ad7636b4fe54310b07404630c6557cd822487b601a6f17/68747470733a2f2f706f7365722e707567782e6f72672f6c65306d2f796969322d62726f616463617374696e672f76657273696f6e)](https://packagist.org/packages/le0m/yii2-broadcasting)[![License](https://camo.githubusercontent.com/a201f850512723b0ae20bb56c27bc86b5b155d61b113a9b52a6453ed2fc63f03/68747470733a2f2f706f7365722e707567782e6f72672f6c65306d2f796969322d62726f616463617374696e672f6c6963656e7365)](https://packagist.org/packages/le0m/yii2-broadcasting)[![Monthly Downloads](https://camo.githubusercontent.com/19242a9fbda284d7c666857889b4aad3ae80875d0fc4c9b0f315f5b02542e8e4/68747470733a2f2f706f7365722e707567782e6f72672f6c65306d2f796969322d62726f616463617374696e672f642f6d6f6e74686c79)](https://packagist.org/packages/le0m/yii2-broadcasting)[![Total Downloads](https://camo.githubusercontent.com/d894337f1c32e660a2606894e1357f3df376e773ffdcc400bfc8ef6fffed0c9b/68747470733a2f2f706f7365722e707567782e6f72672f6c65306d2f796969322d62726f616463617374696e672f646f776e6c6f616473)](https://packagist.org/packages/le0m/yii2-broadcasting)

This component a continuation of [MKiselev/yii2-broadcasting](https://github.com/MKiselev/yii2-broadcasting). It has been re-organized and udpated to work with Yii2 2.0.16.

You can use it to handle notifications through a websocket.

Requirements
------------

[](#requirements)

- a working instance of [laravel-echo-server](https://github.com/tlaverdure/laravel-echo-server), to handle the Socket.io server and channel authentication
- [yiisoft/yii2-redis](https://github.com/yiisoft/yii2-redis) is installed by this package, for sharing messages with Socket.io server through Redis
- [Laravel Echo](https://github.com/laravel/echo) and [socket.io-client](https://github.com/socketio/socket.io-client) on the frontend, to open the websocket and listen for notifications

Installation
------------

[](#installation)

The preferred way to install this extension is through [composer](http://getcomposer.org/download/).

Either run

```
php composer.phar require --prefer-dist le0m/yii2-broadcasting:"~1.0.0"

```

or add

```
"le0m/yii2-broadcasting": "~1.0.0"

```

to the require section of your composer.json.

Configuration
-------------

[](#configuration)

Configure the component to use a broadcaster:

```
'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]);
                },
            ],
        ],
    ]
]
```

There are several broadcast tools available for your choice:

1. [NullBroadcaster](broadcasters/NullBroadcaster.php) Doing nothing, just a stub
2. [LogBroadcaster](broadcasters/LogBroadcaster.php) Broadcast events to application log
3. [RedisBroadcaster](broadcasters/RedisBroadcaster.php) Broadcast by Redis using Pub/Sub feature

Usage
-----

[](#usage)

### Setup Laravel Echo Server

[](#setup-laravel-echo-server)

See [docs](docs/laravel-echo-server.md).

### Server side

[](#server-side)

Add the action to authorize users access to private and presence channels:

```
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'
            ]
        ];
    }

    // ...
}
```

Define a new event to broadcast by extending `le0m\broadcasting\BroadcastEvent`, the public properties you define will be sent as message payload:

```
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;
    }
}
```

And then broadcast it when needed:

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

The `toOthers` flag is used to broadcast a message to all channel's users *except* the sender. The socket ID header is used to exclude the sender.

### Client side

[](#client-side)

Import and initialize `Echo`, then start listening for notifications:

```
import Echo from 'laravel-echo'
import io from 'socket.io-client'

let postId = 13;
const echo = new Echo({
  broadcaster: 'socket.io', // will default to port 6001 of host
  host: window.location.hostname,
  authEndpoint: '/api/rest/v1/notification/auth', // this can be a whole URL
  client: io, // not needed if `io` is globally defined
  auth: {
    headers: {
      Authorization: `Bearer ...` // set headers needed for the authorization request to private and presence channels
    }
  },
  transports: ['websocket', 'polling'] // give websocket precedence
})

// attach connect event listener, to wait for a socket ID
this.echo.connector.socket.on('connect', () => {
  // console.log(`internal socket id:`, this.echo.connector.socket.id)
  console.log(`socket connected with ID:`, this.echo.connector.socketId())

  // attach listen events
  this.echo
    .private(`comments.${postId}`)
    // the initial dot is to ignore event namespace (derived from backend event class)
    .listen('.new', (event) => {
      console.log(`received comment from Echo:`, event)
    })
})
```

Here we wait for the `connect` event of Socket.io connector, to obtain a socket ID before attaching our callbacks.

Other
-----

[](#other)

- [Echo Server with Docker](docs/laravel-echo-server.md) (bottom)
- [references](docs/references.md)
- [changelog](CHANGELOG.md)

###  Health Score

32

—

LowBetter than 72% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity20

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity65

Established project with proven stability

 Bus Factor1

Top contributor holds 63.6% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~337 days

Total

3

Last Release

2550d ago

Major Versions

0.0.2 → 1.0.02019-05-18

### Community

Maintainers

![](https://www.gravatar.com/avatar/36a1b89a62185411675b209cd97652abd29a4e98bd3e68cb5e402bee9ae883d6?d=identicon)[le0m](/maintainers/le0m)

---

Top Contributors

[![MaksimKiselev](https://avatars.githubusercontent.com/u/4495801?v=4)](https://github.com/MaksimKiselev "MaksimKiselev (7 commits)")[![le0m](https://avatars.githubusercontent.com/u/10656716?v=4)](https://github.com/le0m "le0m (3 commits)")[![KoJIT2009](https://avatars.githubusercontent.com/u/3438179?v=4)](https://github.com/KoJIT2009 "KoJIT2009 (1 commits)")

---

Tags

websocketredisyii2extensionechoSocket.ioBroadcasting

### Embed Badge

![Health badge](/badges/le0m-yii2-broadcasting/health.svg)

```
[![Health](https://phpackages.com/badges/le0m-yii2-broadcasting/health.svg)](https://phpackages.com/packages/le0m-yii2-broadcasting)
```

###  Alternatives

[linslin/yii2-curl

Easy and nice cURL extension with RESTful support for Yii2

1811.5M20](/packages/linslin-yii2-curl)[immusen/yii2-swoole-websocket

Websocket server for Yii2 base on swoole 4, Support JSONRPC, Resolve 'method' as a route reflect into controller/action, And support http or redis pub/sub to trigger async task from your web application.

338.8k](/packages/immusen-yii2-swoole-websocket)[joni-jones/yii2-wschat

Online chat based on web sockets and ratchet php

981.3k](/packages/joni-jones-yii2-wschat)[yiiplus/yii2-websocket

使用yii2封装 websocket 扩展

212.6k](/packages/yiiplus-yii2-websocket)[jianyan74/yii2-websocket

yii2 websocket

346.2k1](/packages/jianyan74-yii2-websocket)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
