Skip to content

Commit f33e34e

Browse files
author
joni-jones
committed
Merge pull request #7 from joni-jones/abstract-storage
Added absract storage
2 parents 89bebc8 + 179bc3a commit f33e34e

File tree

15 files changed

+409
-59
lines changed

15 files changed

+409
-59
lines changed

README.md

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,9 @@ Web Socket Chat
33

44
Online chat based on web sockets and ratchet php
55

6+
[![Latest Stable Version](https://poser.pugx.org/joni-jones/yii2-wschat/v/stable)](https://packagist.org/packages/joni-jones/yii2-wschat)
7+
[![Total Downloads](https://poser.pugx.org/joni-jones/yii2-wschat/downloads)](https://packagist.org/packages/joni-jones/yii2-wschat)
8+
[![License](https://poser.pugx.org/joni-jones/yii2-wschat/license)](https://packagist.org/packages/joni-jones/yii2-wschat)
69
[![Join the chat at https://gitter.im/joni-jones/yii2-wschat](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/joni-jones/yii2-wschat?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
710

811
Installation
@@ -27,8 +30,14 @@ to the require section of your `composer.json` file.
2730
Usage
2831
------------
2932

30-
1. Chat use [MongoDB](http://docs.mongodb.org/) and [yii2-mongodb](http://www.yiiframework.com/doc-2.0/ext-mongodb-index.html)
31-
extension to store messages history, so you need just specify connection in `console` config:
33+
1. The chat extension can use any database storage supported by yii.
34+
35+
If `mongodb` extension specified the chat will be try to use it as message history storage, otherwise extension
36+
will be use specified in application config db component.
37+
38+
The simple example how to use mongodb storage is listed below.
39+
Install [MongoDB](http://docs.mongodb.org/) and [yii2-mongodb](http://www.yiiframework.com/doc-2.0/ext-mongodb-index.html)
40+
extension to store messages history and you need just specify connection in `console` config:
3241

3342
```php
3443
'components' => [
@@ -40,6 +49,9 @@ extension to store messages history, so you need just specify connection in `con
4049
```
4150
In created mongodb database you need to create collection named as `history`;
4251

52+
> IMPORTANT: if you use db component - you need to create table `history` in your database.
53+
The simple examples postgresql and mysql you can see in `tests/codeception` directory.
54+
4355
2. To start chat server need to create console command and setup it as demon:
4456

4557
- Create controller which extends `yii\console\controller`:
@@ -118,7 +130,7 @@ In the callback you will get access to ``Chat.Models.ChatRoom`` backbone model.
118130
> If `YII_DEBUG` is enabled - all js scripts will be loaded separately.
119131

120132
Also by default chat will try to load two images:
121-
`/img/avatar_16.png` and `/img/avatar_32.png`
133+
`/img/avatar_16.png` and `/img/avatar_32.png`, but this images are not included to extension.
122134

123135
License
124136
----

assets/js/chat-room.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ Chat.Room.prototype.addConnectionHandlers = function() {
8686
}
8787
};
8888
self.conn.onerror = function (e) {
89-
Helper.Message.error('Current room is not available');
89+
Helper.Message.error('Connection refused');
9090
self.conn.close();
9191
};
9292
self.conn.onmessage = function (e) {

collections/History.php

Lines changed: 49 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
11
<?php
22
namespace jones\wschat\collections;
33

4-
use yii\mongodb\ActiveRecord;
4+
use Yii;
5+
use yii\mongodb\Exception;
6+
use yii\mongodb\Query;
7+
use jones\wschat\components\AbstractStorage;
58

69
/**
710
* Class History
@@ -16,22 +19,63 @@
1619
* @property integer $timestamp
1720
* @property string $message
1821
*/
19-
class History extends ActiveRecord
22+
class History extends AbstractStorage
2023
{
2124
/**
22-
* @inheritdoc
25+
* Get name of mongo collection
26+
*
27+
* @access public
28+
* @static
29+
* @return string
2330
*/
2431
public static function collectionName()
2532
{
2633
return 'history';
2734
}
2835

2936
/**
30-
* @override
37+
* Get list of attributes
38+
*
39+
* @access public
40+
* @return array
3141
*/
3242
public function attributes()
3343
{
34-
return ['_id', 'chat_id', 'chat_title', 'user_id', 'username', 'avatar_16', 'avatar_32', 'timestamp', 'message'];
44+
return [
45+
'_id', 'chat_id', 'chat_title', 'user_id', 'username', 'avatar_16',
46+
'avatar_32', 'timestamp', 'message'
47+
];
48+
}
49+
50+
/**
51+
* @inheritdoc
52+
*/
53+
public function getHistory($chatId, $limit = 10)
54+
{
55+
$query = new Query();
56+
$query->select(['user_id', 'username', 'message', 'timestamp', 'avatar_16', 'avatar_32'])
57+
->from(self::collectionName())
58+
->where(['chat_id' => $chatId]);
59+
if ($limit) {
60+
$query->limit($limit);
61+
}
62+
return $query->all();
63+
}
64+
65+
/**
66+
* @inheritdoc
67+
*/
68+
public function storeMessage(array $params)
69+
{
70+
try {
71+
/** @var \yii\mongodb\Collection $collection */
72+
$collection = Yii::$app->mongodb->getCollection(self::collectionName());
73+
$collection->insert($params);
74+
} catch (Exception $e) {
75+
Yii::error($e->getMessage());
76+
return false;
77+
}
78+
return true;
3579
}
3680
}
3781

components/AbstractStorage.php

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
<?php
2+
namespace jones\wschat\components;
3+
4+
use Yii;
5+
use jones\wschat\collections\History;
6+
7+
/**
8+
* Class AbstractStorage
9+
*
10+
* Base class to create concrete implementer of message storing
11+
* @package jones\wschat\components
12+
*/
13+
abstract class AbstractStorage
14+
{
15+
/**
16+
* Create instance of storage
17+
*
18+
* @access public
19+
* @static
20+
* @param string $storage default null
21+
* @return \jones\wschat\components\AbstractStorage
22+
*/
23+
public static function factory($storage = null)
24+
{
25+
if (empty($storage)) {
26+
$components = Yii::$app->getComponents();
27+
$storage = !empty($components['mongodb']) ? 'mongodb' : Yii::$app->getDb()->driverName;
28+
}
29+
switch ($storage) {
30+
case 'mongodb':
31+
$class = new History();
32+
break;
33+
default:
34+
$class = new DbStorage();
35+
}
36+
return $class;
37+
}
38+
39+
/**
40+
* Load chat history
41+
*
42+
* @access public
43+
* @param mixed $chatId
44+
* @param integer $limit
45+
* @return array
46+
*/
47+
abstract public function getHistory($chatId, $limit = 10);
48+
49+
/**
50+
* Store chat message
51+
*
52+
* @access public
53+
* @param array $params
54+
* @return boolean
55+
*/
56+
abstract public function storeMessage(array $params);
57+
}

components/ChatManager.php

Lines changed: 12 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,6 @@
33

44
use Yii;
55
use jones\wschat\collections\History;
6-
use yii\mongodb\Exception;
7-
use yii\mongodb\Query;
86

97
/**
108
* Class ChatManager
@@ -144,22 +142,17 @@ public function removeUserFromChat($rid)
144142
*/
145143
public function storeMessage(User $user, ChatRoom $chat, $message)
146144
{
147-
try {
148-
/** @var \yii\mongodb\Collection $collection */
149-
$collection = Yii::$app->mongodb->getCollection(History::collectionName());
150-
$collection->insert([
151-
'chat_id' => $chat->getUid(),
152-
'chat_title' => $chat->title,
153-
'user_id' => $user->getId(),
154-
'username' => $user->username,
155-
'avatar_16' => $user->avatar_16,
156-
'avatar_32' => $user->avatar_32,
157-
'message' => $message['message'],
158-
'timestamp' => $message['timestamp']
159-
]);
160-
} catch (Exception $e) {
161-
Yii::error($e->getMessage());
162-
}
145+
$params = [
146+
'chat_id' => $chat->getUid(),
147+
'chat_title' => $chat->title,
148+
'user_id' => $user->getId(),
149+
'username' => $user->username,
150+
'avatar_16' => $user->avatar_16,
151+
'avatar_32' => $user->avatar_32,
152+
'message' => $message['message'],
153+
'timestamp' => $message['timestamp']
154+
];
155+
AbstractStorage::factory()->storeMessage($params);
163156
}
164157

165158
/**
@@ -172,14 +165,7 @@ public function storeMessage(User $user, ChatRoom $chat, $message)
172165
*/
173166
public function getHistory($chatId, $limit = 10)
174167
{
175-
$query = new Query();
176-
$query->select(['user_id', 'username', 'message', 'timestamp', 'avatar_16', 'avatar_32'])
177-
->from(History::collectionName())
178-
->where(['chat_id' => $chatId]);
179-
if ($limit) {
180-
$query->limit($limit);
181-
}
182-
return $query->all();
168+
return AbstractStorage::factory()->getHistory($chatId, $limit);
183169
}
184170
}
185171

components/DbStorage.php

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
<?php
2+
namespace jones\wschat\components;
3+
4+
use yii;
5+
use yii\db\Query;
6+
use yii\db\Exception;
7+
8+
/**
9+
* Class DbStorage
10+
*
11+
* This class is database storage implementation for chat messages storing
12+
* @package jones\wschat\components
13+
*/
14+
class DbStorage extends AbstractStorage
15+
{
16+
/**
17+
* Get name of table
18+
*
19+
* @access public
20+
* @static
21+
* @return string
22+
*/
23+
public static function tableName()
24+
{
25+
return 'history';
26+
}
27+
28+
/**
29+
* Get list of attributes
30+
*
31+
* @access public
32+
* @return array
33+
*/
34+
public function attributes()
35+
{
36+
return [
37+
'id', 'chat_id', 'chat_title', 'user_id', 'username', 'avatar_16',
38+
'avatar_32', 'timestamp', 'message'
39+
];
40+
}
41+
42+
/**
43+
* @inheritdoc
44+
*/
45+
public function getHistory($chatId, $limit = 10)
46+
{
47+
$query = new Query();
48+
$query->select(['user_id', 'username', 'message', 'timestamp', 'avatar_16', 'avatar_32'])
49+
->from(self::tableName())
50+
->where(['chat_id' => $chatId]);
51+
if ($limit) {
52+
$query->limit($limit);
53+
}
54+
return $query->all();
55+
}
56+
57+
/**
58+
* @inheritdoc
59+
*/
60+
public function storeMessage(array $params)
61+
{
62+
try {
63+
Yii::$app->getDb()->createCommand()
64+
->insert(self::tableName(), $params)
65+
->execute();
66+
} catch (Exception $e) {
67+
Yii::error($e->getMessage());
68+
return false;
69+
}
70+
return true;
71+
}
72+
}
73+

0 commit comments

Comments
 (0)