author: Christian Salazar. christiansalazarh@gmail.com
GIT Repository at: https://bitbucket.org/christiansalazarh/yiichat
YiiChat ¶
The most simple jQuery based chat in the world for Yii based applications. YiiChat is an abstract chat component. By default YiiChat comes with a ready-for-use database handler. You can provide your own class or mechanism to provide real data to this chat.
Basic Installation ¶
1) Clone it using GIT. Or perform a direct download from repository download ~~~ $ cd /home/yourapp/protected/extensions $ git clone https://bitbucket.org/christiansalazarh/yiichat.git ~~~
2) In config/main, in your imports, add:
'imports'=>array(
..bla..
'application.extensions.yiichat.*',
),
3) Edit your file: 'protected/controllers/siteController.php' and add the static action int actions() array. This step is required ONCE no matter if your application inserts more than one yiichat widgets.
class SiteController extends Controller
{
public function actions()
{
return array(
'captcha'=>array(
'class'=>'CCaptchaAction',
'backColor'=>0xFFFFFF,
),
'page'=>array(
'class'=>'CViewAction',
),
'yiichat'=>array('class'=>'YiiChatAction'), // <- ADD THIS LINE
);
}
..bla..
}
4) Setup widget. IMPORTANT: please note the 'model'=>new MyYiiChatHandler(). this is a demo handler to shows you the minimal requirements for provide demo data to this chat. It uses no database. For database please read about: "Using Yii Chat with a Database" (next topic).
<h1>Yii Chat Demo</h1>
<div id='chat'></div>
<?php
$this->widget('YiiChatWidget',array(
'chat_id'=>'123', // a chat identificator
'identity'=>1, // the user, Yii::app()->user->id ?
'selector'=>'#chat', // were it will be inserted
'minPostLen'=>2, // min and
'maxPostLen'=>10, // max string size for post
'model'=>new MyYiiChatHandler(), // the class handler. **** FOR DEMO, READ MORE LATER IN THIS DOC ****
'data'=>'any data', // data passed to the handler
// success and error handlers, both optionals.
'onSuccess'=>new CJavaScriptExpression(
"function(code, text, post_id){ }"),
'onError'=>new CJavaScriptExpression(
"function(errorcode, info){ }"),
));
?>
5) STEP FIVE is in topic: "Using Yii Chat with a Database" only required if you want this widget using the provided database mechanism.
Using Yii Chat with a Database ¶
1) Create a new file named: "protected/components/ChatHandler.php" having this content:
<?php
class ChatHandler extends YiiChatDbHandlerBase {
//
// IMPORTANT:
// in any time here you can use this available methods:
// getData(), getIdentity(), getChatId()
//
protected function getDb(){
// the application database
return Yii::app()->db;
}
protected function createPostUniqueId(){
// generates a unique id. 40 char.
return hash('sha1',$this->getChatId().time().rand(1000,9999));
}
protected function getIdentityName(){
// find the identity name here
// example:
// $model = MyPeople::model()->findByPk($this->getIdentity());
// return $model->userFullName();
return "jhonn doe";
}
protected function getDateFormatted($value){
// format the date numeric $value
return Yii::app()->format->formatDateTime($value);
}
protected function acceptMessage($message){
// return false to reject it, elsewere return $message
return $message;
}
}
?>
2) In your widget setup, change the model attribute, by the following value:
'model'=>new ChatHandler(), // the class handler using database
3) In your database, create the yii_chat table, using the following sql script:
(you can import the provided: "post.sql" script provided in the yiichat package)
~~~
[sql]
/ mysql /
CREATE TABLE yiichat_post
(
id
CHAR(40),
chat_id
CHAR(40) NULL ,
post_identity
CHAR(40) NULL ,
owner
CHAR(20) NULL ,
created
BIGINT(30) NULL ,
text
BLOB NULL ,
data
BLOB NULL ,
PRIMARY KEY (id
) ,
INDEX yiichat_chat_id
(chat_id
ASC),
INDEX yiichat_chat_id_identity
(chat_id
ASC, post_identity
ASC)
)ENGINE = InnoDB;
~~~
Using the ChatHandler.php ¶
The ChatHandler.php file provides an extension for your application, in this file you are required to provide the database connection, create a sequential unique id for each post, etc etc, it serves for you to kwnow about incoming messages.
Did you see the "jhonn doe" user name always in your chat ?
This is because you must provide the way in how to recognize the user in your own database returning the name in the getIdentityName() method using the getIdentity() value to recognize it. In the widget configuration you pass a "chat_id" and an "identity", this Identity is current user identificator (it can be Yii::app()->user->id).
As an example, when a new message arrives it is catched and sent to your ChatHandler, you can accept or reject it or take your own actions usign the provided acceptMessage() method.
You can use: getData(), getIdentity() and getChatId() all the time to read the current widget arguments, the same widget can be used by many different users, you recognize them by getIdentity(). If you are using Yiichat in an view common for all your people (leaving behind the rbac issued for now) then the unique way you have in yiichat to check wich user is sending a specific message is reading the $this->getIdentity(), in this way you can difference which user is sending the post. The chat_id is your business, you are required to provide and connect your chat to your existing model and in consecuence to give a chat_id to this widget. The getData() is the same passed to the widget argument.
YiiChat Internals ¶
Nerd Zone. Be Aware.
Data Mechanism Provided by YiiChat ¶
The widget must be configured using a "model" for save and retrieve the messages, this "model" must implements an specific IYiiChat Interface, by default and for help the developper the yiichat extension comes with a MyYiiChatHandler.php who implements this required interface, this demo handler shows you the minimal requirements to implement your own data model.
In adittion, and again, to help the developper to rapid start, the yiichat comes with another specific class named YiiChatDbHandlerBase.php, this class implements the required IYiiChat Interface too, but as different as the demo handler it uses a database to save and restore the messages using an specific mysql table named yii_post.
This YiiChatDbHandlerBase.php is an abstract class, so you can't use it directly, so, in order to give you an extension for your own code and needs you are required to create a new class extending the YiiChatDbHandlerBase.php, and, use the provided methods to serve your own application. See also: ChatHandler.php up later in this article.
In resume, you can create any class that implements IYiiChat Interface, and it can serve the yiichat extension, but for rapid development i create the class YiiChatDbHandlerBase.php in were you can extends a new class for you (the ChatHandler.php).
Rbac and BizRules ¶
Your yii auth mechanism must include a bizrule as aditional rbac rule. This is due to the following situation you could have in your application:
Suppose all your users has assigned the role named "CHAT USERS". This role only ensures that they can give access to -the action in a controller- having a yiichat widget view. But, what happens when you must ensure a subset of users chating in one specific "chat_id", denying the others users to give access to this specific chat_id ? This work is done by the bizrule.
This wiki is not focused in show you how to use a rbac and a bizrule, it is a large theme. The Yiichat widget has no responsability to offer a way to incorporate access control, this work is done by the Yii Authentication, not yiichat.
wowWww
Woow... i like this.
please sample database or demo.
Thanks
Database Support
please read about database support. it is very easy to implement. only 3 simple steps and you a functional chat using your database.
gr8!!
I have implemented it successfully..
thanx
How to save in database ??
Can you please tel me how to save these chat in db.. ?? and also tel how to view the online status of the users ??
to @newgirl
hi @newgirl,
yiichat offers you a very basic chat functionality, not a user functionality this is your work because can vary so much between developpers and desitions, so yiichat provides the minimum: "a message in and out UI feature for a specific chatid and userid"
in respect to DB, you will found the "Step #5" in site:
http://www.yiiframework.com/extension/yiichat/
this step shows you how to implement the storage, basically you must create your own handler: protected/components/ChatHandler.php
and tell YiiChat widget your are using it instead of the default,
'model'=>new ChatHandler(),
this single steps allows you to save the chat messages into a database,
PHP warning
include(CJavaScriptExpression.php): failed to open stream: No such file or directory
<?php
$this->widget('YiiChatWidget',array( 'chat_id'=>'123', 'identity'=>1, 'selector'=>'#chat', 'minPostLen'=>2, 'maxPostLen'=>10, 'model'=>new MyYiiChatHandler(), 'data'=>'any data', // success and error handlers, both optionals. 'onSuccess'=>new CJavaScriptExpression( // here "function(code, text, post_id){ }"), //here 'onError'=>new CJavaScriptExpression( "function(errorcode, info){ }"), ));
?>
about CJavaScriptExpression
requires Yii 13 or higher, if you cant move to yii 13 then copy the class from yii 13 yii repo into your own framework.
return 1 in chat
I followed the guide step by step, is recorded correctly but what I write in the chat box and the database is stored only 1 per entry instead of your text
he seguido la guía paso a paso, se registra correctamente lo que escribo pero en el recuadro de chat y en la base de datos se almacena solo un 1 por cada entrada en lugar de su texto
Thank you
Thank you for this great extension!
to @Enekoos
Hi
This may help you :
In the ChatHandler.php -> function acceptMessage($message)
Add this :
return $message;
Instead of :
return true;
The form fields are disbled
After integrated with mycode the chat textbox and send buttons are disabled why?
not working
I did what you said but I only got a small textarea and a 'Send' button. When clicking on 'Send' nothing happens.
to @moginn
Hi @moginn, it is possible when your jQuery version is outdated. Review your browser console for errors.
Notification
how i get notification whenvr a new message from user..ELse tel where i have to put code to check new row has been added ??plzzzzzzzzzzzzz
how to retrieve a last post
Hi
The chat extension works well but it won't updates a new row added...i want to update a new row added automatically..Plz tell..i used a refresh a particular div alone but i want to reload a page whenever a new message came ??
I followed all steps, chat window also appeared, but on click the send button gives the following error
Error
Call to a member function yiichat_list_posts() on null (C:\xampp\htdocs\liveprojects\halopinNew\protected\extensions\yiichat\YiiChatWidget.php:128)
If you have any questions, please ask in the forum instead.
Signup or Login in order to comment.