PHPackages                             blackbes/yii2-yiisockets - 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. [Utility &amp; Helpers](/categories/utility)
4. /
5. blackbes/yii2-yiisockets

ActiveYii2-extension[Utility &amp; Helpers](/categories/utility)

blackbes/yii2-yiisockets
========================

1.0.1(4y ago)10MITPHP

Since Jul 12Pushed 4y ago2 watchersCompare

[ Source](https://github.com/BlackBes/yii2-yiisockets)[ Packagist](https://packagist.org/packages/blackbes/yii2-yiisockets)[ RSS](/packages/blackbes-yii2-yiisockets/feed)WikiDiscussions master Synced 2d ago

READMEChangelog (1)Dependencies (3)Versions (1)Used By (0)

Websockets for Yii2
===================

[](#websockets-for-yii2)

PHP Websockets with Yii2 integration based on Ratchet.

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

[](#installation)

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

1. **Clone** this project in any directory. In this case it will be located in upper level folder

```
    cd ..
    git clone https://github.com/BlackBes/yii2-yiisockets.git
```

2. In your project's **composer.lock** add following lines:

```
    "require": {
        ...
        "blackbes/yii2-yiisockets": "@dev",
        ...
    },

    ...

    "repositories": [
        ...
        {
            "type": "path",
            "url": "../yii2-yiisockets"
        }
        ...
    ]

```

3. Run composer install in the project root

```
    composer install
```

4. Add following lines to your **config/console.php**. **Note** that provided model should be the one you use to perform authorisation in your app. (Should implement Identity Interface)

```
    'components' => [
        ...
        'user' => [
            'class' => 'yii\web\User',
            'identityClass' => 'app\models\',
            'enableAutoLogin' => true
        ],
        ...
    ]

```

5. Add **SocketController.php** (you can find template [here](https://github.com/BlackBes/yii2-yiisockets/blob/master/templates/SocketController.php)) to your **commands** folder
6. Add **ecosystem.config.js** (you can find template [here](https://github.com/BlackBes/yii2-yiisockets/blob/master/templates/ecosystem.config.js)) to your project **root** directory
7. Install [**npm**](https://linuxize.com/post/how-to-install-node-js-on-ubuntu-18.04/)
8. Install **pm2**

```
    npm i pm2 -g
```

Usage on back
-------------

[](#usage-on-back)

1. Create **sockets** folder in your root directory
2. Add controllers that extends **blackbes\\yiisockets\\BaseController**
3. Start server
4. Start pm2

BaseController Overview
-----------------------

[](#basecontroller-overview)

Extending this controller will provide following methods that you can use in your websocket controllers:

MethodParametersReturnsExample usagesend()**ConnectionInterface** $conn, **string** $group\_id, **mixed** datanone$this-&gt;send($this-&gt;conn, 'get-new-text', \['text' =&gt; $text\]);sendError()**ConnectionInterface** $conn, **string** $error\_textnone---sendToGroupExcludeClient()**string** $action, **mixed** $data, **string** $group\_id, **bool** $is\_json**boolean**$this-&gt;sendToGroup('new-message', \['text' =&gt; $text\], 'chat-'.$chatId);sendToGroupExcludeUser()**string** $action, **mixed** $data, **string** $group\_id, **bool** $is\_json**boolean**$this-&gt;sendToGroup('new-message', \['text' =&gt; $text\], 'chat-'.$chatId);sendToGroup()**string** $action, **mixed** $data, **string** $group\_id, **bool** $is\_json**boolean**$this-&gt;sendToGroup('new-message', \['text' =&gt; $text\], 'chat-'.$chatId);addToGroup()**ConnectionInterface** $conn, **string** $group\_id**boolean**$this-&gt;addToGroup($this-&gt;conn,'chat-'.$chatId);removeFromGroup()**ConnectionInterface** $conn, **string** $group\_id**boolean**$this-&gt;removeFromGroup($this-&gt;conn,'chat-'.$chatId);isInGroup()**ConnectionInterface** $conn, **string** $group\_id**boolean**---GetGroup()**string** $group\_id**mixed** - All connections from specific group---getClientId()**ConnectionInterface** $conn**integer** - Id of user---getData()**string** $data\_name**mixed** - Specified value that you've sent in request$this-&gt;getData('chatId')Connecting to websockets on front
---------------------------------

[](#connecting-to-websockets-on-front)

1. Add [**Yii2WebSockets**](https://github.com/BlackBes/yii2-yiisockets/blob/master/templates/yiisockets-core.js) file to your JavaScript project and import it

    ```
       import Yii2WebSockets from "path/to/yiisockets-core";
    ```
2. Create a variable object **login\_credentials** with following properties:

    ```
         let login_tokens = {
             'login-token': authToken, //Auth token that your identity uses to log in
             'connection-type': 'user'
         };
    ```
3. Start WebSocket connection

    ```
        let _ws = new Yii2WebSockets(login_credentials);

        _ws.connect(socketAddress, socketPort, socketMode, socketRoute);

          // Default values are
          //   - socketAddress = 'localhost';
          //   - socketPort = '8088';
          //   - socketMode = 'ws';
          //   - socketRoute = '';
    ```
4. Add actions to listen to. Those will trigger when one of your contollers will use a sendToGroup() method which has same action name

    ```
        let actionToListenTo = 'new-message' //this is for example

       _ws.addAction(action, function (data) {
            console.log(data) //here you decide what to do with data, when it arrives
        });
    ```

    Note that you can add multiple actions

Using websockets on front
-------------------------

[](#using-websockets-on-front)

1. Use socketSend method to make requests ```
        let actionName = 'chat/send' // chat - controller name, send - controller's action (actionSend(){})
        let additionalData = {'text': "some example text"} // this property you can get in controller by using $this->getData('text')
        ws.socketSend(actionName, additionalData);
    ```
2. Process responses in your addAction methods

###  Health Score

22

—

LowBetter than 22% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity2

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity49

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% 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

Unknown

Total

1

Last Release

1765d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/2f2d819274b1214339532eb7c25cc462dd8959da6d27b1b5b719179da51aacba?d=identicon)[BlackBes](/maintainers/BlackBes)

---

Top Contributors

[![yskrypnyk](https://avatars.githubusercontent.com/u/51512763?v=4)](https://github.com/yskrypnyk "yskrypnyk (7 commits)")

---

Tags

socketsWebSocketsyii2extensionratchet with yii2

### Embed Badge

![Health badge](/badges/blackbes-yii2-yiisockets/health.svg)

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

###  Alternatives

[dmstr/yii2-cookie-consent

Yii2 Cookie Consent Widget

1452.6k](/packages/dmstr-yii2-cookie-consent)[richardfan1126/yii2-js-register

Yii2 widget to register JS into view

1357.2k7](/packages/richardfan1126-yii2-js-register)

PHPackages © 2026

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