PHP code example of werwolflg / yii2-wschat

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

    

werwolflg / yii2-wschat example snippets


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

        ServerController extends \yii\console\Controller
        

        namespace app\commands;

        use werwolflg\wschat\components\Chat;
        use werwolflg\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;
            }
        }
        

        yii server/run
        
  
        <?= ChatWidget::widget([
            'auth' => true,
            'user_id' => Yii::$app->user->id // setup id of current logged user
        ]) 

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