s4studio/yii2-wschat 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

s4studio/yii2-wschat

Composer 安装命令:

composer require s4studio/yii2-wschat

包简介

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

README 文档

README

Online chat based on web sockets and ratchet php. Forked: https://github.com/svbackend/yii2-wschat (public chat, with rooms). Removed MongoDB dependency as required one.

Installation

The preferred way to install this extension is through composer.

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

  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 and yii2-mongodb 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:

        <?= ChatWidget::widget([
            'auth' => true,
            'user_id' => Yii::$app->user->id // setup id of current logged user
        ]) ?>
     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

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

MIT

s4studio/yii2-wschat 适用场景与选型建议

s4studio/yii2-wschat 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 101 次下载、GitHub Stars 达 0, 最近一次更新时间为 2018 年 10 月 25 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「websocket」 「extension」 「backbone」 「Ratchet」 「chat」 「yii2」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 s4studio/yii2-wschat 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 s4studio/yii2-wschat 我们能提供哪些服务?
定制开发 / 二次开发

基于 s4studio/yii2-wschat 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 101
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 6
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 1
  • Forks: 3
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2018-10-25