PHPackages                             s4studio/yii2-wschat - 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. s4studio/yii2-wschat

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

s4studio/yii2-wschat
====================

Private chat based on web sockets and ratchet php (Yii2)

0.2(7y ago)0101MITPHP

Since Aug 9Pushed 7y ago1 watchersCompare

[ Source](https://github.com/s4studio/yii2-wschat)[ Packagist](https://packagist.org/packages/s4studio/yii2-wschat)[ RSS](/packages/s4studio-yii2-wschat/feed)WikiDiscussions master Synced today

READMEChangelog (1)Dependencies (13)Versions (5)Used By (0)

Yii2 Web Socket Private Chat
============================

[](#yii2-web-socket-private-chat)

Online chat based on web sockets and ratchet php. Forked:  (public chat, with rooms). Removed MongoDB dependency as required one.

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

[](#installation)

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

Either run

```
php composer.phar require --prefer-dist s4studio/yii2-wschat

```

or add

```
"s4studio/yii2-wschat": "*"

```

to the require section of your `composer.json` file.

Usage
-----

[](#usage)

1. The chat extension can use any database storage supported by yii.

    If you would like to use **mysql/mariadb** server keep your current DB configuration and simply import table:

    ```
        CREATE TABLE IF NOT EXISTS `history` (
          `id` int(11) NOT NULL,
          `chat_id` varchar(60) COLLATE utf8_unicode_ci DEFAULT NULL,
          `chat_title` varchar(60) COLLATE utf8_unicode_ci DEFAULT NULL,
          `user_id` varchar(60) COLLATE utf8_unicode_ci DEFAULT NULL,
          `username` varchar(60) COLLATE utf8_unicode_ci DEFAULT NULL,
          `avatar_16` varchar(90) COLLATE utf8_unicode_ci DEFAULT NULL,
          `avatar_32` varchar(90) COLLATE utf8_unicode_ci DEFAULT NULL,
          `timestamp` int(11) NOT NULL DEFAULT '0',
          `message` text COLLATE utf8_unicode_ci
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

        ALTER TABLE `history`
          ADD PRIMARY KEY (`id`);

        ALTER TABLE `history`
          MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
    ```

    If `mongodb` extension specified the chat will be try to use it as message history storage, otherwise extension will be use specified in application config db component.

    The simple example how to use mongodb storage is listed below. Install [MongoDB](http://docs.mongodb.org/) and [yii2-mongodb](http://www.yiiframework.com/doc-2.0/ext-mongodb-index.html)extension to store messages history and you need just specify connection in `console` config:

    ```
        'components' => [
            'mongodb' => [
                'class' => '\yii\mongodb\Connection',
                'dsn' => 'mongodb://username:password@localhost:27017/dbname'
            ]
        ]
    ```

    In created mongodb database you need to create collection named as `history`;
2. To start chat server need to create console command and setup it as demon:

    - Create controller which extends `yii\console\Controller`:

        ```
        ServerController extends \yii\console\Controller
        ```
    - Create action to start server:

        ```
        namespace app\commands;

        use s4studio\wschat\components\Chat;
        use s4studio\wschat\components\ChatManager;
        use Ratchet\Server\IoServer;
        use Ratchet\Http\HttpServer;
        use Ratchet\WebSocket\WsServer;

        class ServerController extends \yii\console\Controller
        {
            public function actionRun()
            {
                $manager = Yii::configure(new ChatManager(), [
                    'userClassName' => Users::class, // Your User Active Record model class
                ]);
                $server = IoServer::factory(new HttpServer(new WsServer(new Chat($manager))), 8080);

                // If there no connections for a long time - db connection will be closed and new users will get the error
                // so u need to keep connection alive like that
                // Что бы база данных не разрывала соединения изза неактивности
                $server->loop->addPeriodicTimer(60, function () use ($server) {
                    try{
                        Yii::$app->db->createCommand("DO 1")->execute();
                    }catch (Exception $e){
                        Yii::$app->db->close();
                        Yii::$app->db->open();
                    }
                    // Also u can send messages to your cliens right there
                    /*
                    foreach ($server->app->clients as $client) {
                        $client->send("hello client");
                    }*/
                });

                $server->run();
                echo 'Server was started successfully. Setup logging to get more details.'.PHP_EOL;
            }
        }
        ```
    - Now, you can run chat server with `yii` console command:

        ```
        yii server/run
        ```
3. To add chat on page just call:

    ```

    ```

    ```
     List of available options:
     auth - boolean, default: false
     user_id - mixed, default: null
     port - integer, default: 8080
     chatList - array (allow to set list of preloaded chats), default: [
         id => 1,
         title => 'All'
     ],
     add_room - boolean, default: true (allow to user create new chat rooms)

    ```

You can also store added chat, just specify js callback for vent events:

```
Chat.vent('chat:add', function(chatModel) {
    console.log(chatModel);
});

```

This code snipped may be added in your code, but after chat widget loading. In the callback you will get access to `Chat.Models.ChatRoom` backbone model. Now, you need add your code to save chat room instead `console.log()`.

> If `YII_DEBUG` is enabled - all js scripts will be loaded separately.

Also by default chat will try to load two images: `/avatar_16.png` and `/avatar_32.png` from assets folder.

Possible issues
---------------

[](#possible-issues)

If you don't see any messages in console log, check `flushInterval` and `exportInterval` of your log configuration component. The simple configuration may looks like this:

```
'log' => [
    'traceLevel' => YII_DEBUG ? 3 : 0,
    'flushInterval' => 1,
    'targets' => [
        [
            'class' => 'yii\log\FileTarget',
            'levels' => ['error', 'warning', 'info'],
            'logVars' => [],
            'exportInterval' => 1
        ],
    ],
],
```

License
-------

[](#license)

MIT

###  Health Score

26

—

LowBetter than 43% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity9

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity56

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 60% 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 ~147 days

Total

4

Last Release

2756d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/1bb0203a0513468d82ada30651fe5a49e4ed2a11276652e6e9e63636144d873c?d=identicon)[ekawalec](/maintainers/ekawalec)

---

Top Contributors

[![ekawalec](https://avatars.githubusercontent.com/u/9531269?v=4)](https://github.com/ekawalec "ekawalec (9 commits)")[![svbackend](https://avatars.githubusercontent.com/u/19356345?v=4)](https://github.com/svbackend "svbackend (6 commits)")

---

Tags

websocketyii2extensionRatchetchatbackbone

###  Code Quality

TestsCodeception

### Embed Badge

![Health badge](/badges/s4studio-yii2-wschat/health.svg)

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

###  Alternatives

[joni-jones/yii2-wschat

Online chat based on web sockets and ratchet php

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

Yii2 websocket server component

9275.9k2](/packages/consik-yii2-websocket)[linslin/yii2-curl

Easy and nice cURL extension with RESTful support for Yii2

1811.5M20](/packages/linslin-yii2-curl)[skeeks/cms

SkeekS CMS — control panel and tools based on php framework Yii2

13825.6k47](/packages/skeeks-cms)[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)[yiiplus/yii2-websocket

使用yii2封装 websocket 扩展

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

PHPackages © 2026

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